How to sort array of numbers in C -
i'm trying sort array using function findminimumindex in loop, can't seem find it's not sorting correctly. suggestions? function works fine, when try use in loop, doesn't work. suggestions? thanks!
int findminimumindex(a[], int a, int b); //finds smallest index of portion of array (a[i] ... a[j]) int main(){ int a[5] = {4,6,7,4,3}; int smallest_index; (int j = 0; j < count; j++){ smallest_index = findminimumindex(a, j, 4); printf("sorted: %d\n", a[smallest_index]); } } int findminimumindex(int a[], int a, int b){ int smallest_value = a[a]; int index = 0; (int k = a; k < j - 1; k++){ if (a[k + 1] < smallest_value){ smallest_value = a[k+1]; index = k + 1; } } return index; }
if find minimum value , index, should switch values:
look @ example:
you have got array:
{4,6,7,4,3}
at first, find value 3
@ index 4
, have move smallest value (switch value on j=0
index):
{3,6,7,4,4}
then find 4
on index 3
, then, switch j=1
:
{3,4,7,6,4}
etc.
modification of code:
for (int j = 0; j < count; j++){ smallest_index = findminimumindex(a, j, 4); int tmp = a[smallest_index]; a[smallest_index] = a[j]; a[j] = tmp; printf("sorted: %d\n", a[j]); }
edit: correction:
length of array 5:
smallest_index = findminimumindex(a, j, 5);
and index should set a
int findminimumindex(int a[], int a, int b){ int smallest_value = a[a]; int index = a; /* code */ }
Comments
Post a Comment