Im trying to learn C and I'm doing this program to sort an array but It doesn't work and I'm not sure why, I tested each function and works well, someone knows if its a problem of variables or something?
#include <stdio.h>
#include <stdlib.h>
#define N 5
int V[5] = { -383, 386, 277, 415, 293 };
void displayArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
}
int maxim(int v[], int n)
{
int i, m;
m = v[0];
/*
Find maxim element
*/
for (i = 1; i < n; i++)
if (v[i] > m)
m = v[i];
/*
Search element position
*/
for (i = 0; i < N; i++)
if (v[i] == m)
return i;
}
void sort(int v[], int n)
{
int i, pos, t;
for (i = 0; i < n; i++)
pos = maxim(v, n - i);
/*
Swap elements
*/
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
}
int main()
{
displayArray(V, N);
sort(V, N);
printf("\n");
displayArray(V, N);
return 0;
}
The output is
-383 386 277 415 293
- Original Array
21900 386 277 415 293
- 'Sorted' Array
First fix your maxim
function. Its purpose is to find the maximum index of a sequence v
of magnitude n
. Therefore, remembering the maximum value in m
is irrelevant; you want to remember where it resides :
int maxim(int v[], int n)
{
int m=0;
for (int i=1; i<n; ++i)
{
if (v[m] < v[i])
m = i; // save new max location
}
return m;
}
After that, the sort, which is completely wrong. This:
int i, pos, t;
for (i = 0; i < n; i++)
pos = maxim(v, n - i);
is pointless. It calculates, and overwrites, pos
repeatedly until the last iteration, which is the only one that is processed with:
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
E..g, you sort one element, and then exit your sort. You need to sort them all , starting with the full segment, then reducing the size of the segment by one with each iteration after you swap the most-maximum element into position for that segment.
void sort(int v[], int n)
{
for (int i=0; i<(n-1); ++i)
{
int m = maxim(v, (n-i)); // max of this segment
int tmp = v[m];
v[m] = v[n-i-1];
v[n-i-1] = tmp;
}
}
pos = maxim(v, n - i);
should be
pos = maxim(v, n);
Your program is inefficient, but almost correct. The only place where you must focus is:
void sort(int v[], int n)
{
int i, pos, t;
for (i = 0; i < n; i++)
pos = maxim(v, n - i);
/*
Swap elements
*/
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
}
Well, C is not Python, so if, after getting pos
you want to swap the elements of your array, then you need to group all of the for
loop in braces, as in:
void sort(int v[], int n)
{
int i, pos, t;
for (i = 0; i < n; i++) {
pos = maxim(v, n - i);
/*
Swap elements
*/
t = v[n - 1 - i];
v[n - 1 - i] = v[pos];
v[pos] = t;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.