c - Different even and odd sorting in Quicksort -
i've got such algorithmic problem: need make quicksort work this:
1) indexes of array odd numbers should sorted smallest largest
2) indexes should sorted largest smallest.
so if we've got array: 2 5 1 3 4 0 6 2 5, should sth like: 6 0 5 2 4 3 2 5 1
here implementation of quicksort in c:
void quicksort(int tab[], int start, int end) { int i=start; int j=end; int x=tab[(i+j)/2]; { while(tab[i]<x) i++; while(tab[j]>x) j--; if(i<=j) { int tmp=tab[i]; tab[i]=tab[j]; tab[j]=tmp; i++; j--; } } while(i<=j); if(start<j) quicksort(tab,start,j); if(i<end) quicksort(tab,i,end); }
is possible make using 1 quicksort or should try sth creating 2 functions: 1 sort odd indexes , second 1 indexes?
is possible make using 1 quicksort or should try sth creating 2 functions: 1 sort odd indexes , second 1 indexes?
quick sort
used sort elements in ascending or descending order don't think it'd useful sort elements in required pattern ( neither ascending nor descending , no particular pattern guaranteed in answer array ) usingquick sort
.
in opinion creating additional custom function
required_sort()
, sort elements required along ofqucksort()
(here in case sorts in ascending order) best way go
void required_sort(int array[], int size_of_array) { int no_of_even_elements, no_of_odd_elements if(size_of_array%2 == 0) { no_of_even_elements = no_of_odd_elements = n/2; } else { no_of_even_elements = (n/2)+1; no_of_odd_elements = n/2; } int even[no_of_even_elements], odd_even[elements]; //inserting elements new arrays for(int index=0; index < size_of_array; index++) { if(index%2 == 0) { even[index/2] = array[index]; } else { odd[index/2] = array[index]; } } //call quicksort function sort even[] array in ascending order //call quicksort function sort odd[] array in ascending order for(int index=0; index < size_of_array; index++) { if(index%2 == 0) { array[index] = even[(no_of_even_elements)-(index/2)]; } else { array[index] = odd[index/2]; } } }
explanation of required_sort
:
- first check whether
size_of_array
even or odd if
size_of_array
even there equal number of elements @ odd indices , indices.no_of_even_elements = no_of_odd_elements = n/2
if
size_of_array
odd there equal number of elements @ odd indices , indices. sono_of_even_elements = (n/2)+1 no_of_odd_elements = n/2
create 2 more arrays.
odd[no_of_odd_elements]
,even[no_of_even_elements]
- in first array store elements @ odd indices , in second elements @ even indices.
- use
quicksort()
(in ascending order) sort both arrays now using
for
loop update values of originalarray[]
way :for(int index=0; index < size_of_array; index++) { if(index%2 == 0) { array[index] = even[(no_of_even_elements)-(index/2)]; } else { array[index] = odd[index/2]; } }
hope helps :)
Comments
Post a Comment