Quick sort programmed in C

南楼画角 提交于 2019-12-02 13:31:06

Firstly, you have a small misconception about the swap function. Let's say the prototype of the function is -

swap(int array[], int i, int j)

The swap function swaps the numbers at location array[i] and array[j]. So, the swap function swaps the elements in the array. So, the line -

swap(v, left, (left + right) / 2);

Means that, the middle element in the array is swapped with the leftmost element. Clearly, the quicksort is taking the middle element as the pivot. This swap has no effect on the local variables or parameters. According to your data input example, the value of 'left' = 0, and the value of right = '8', even after the swapping. This is where you got confused. The elements of array are swapped, not the values of variables. So, now, the line -

last = left;

makes, 'last' point to the location of the pivot ('left'), so here the value of 'last' = 0 not 4. So, the loop,

for(i = left + 1; i <= right; i++) 

Runs from i = 1 to 8. BTW, you forgot the semicolon..! Then, the line,

if(v[i] < v[left])

checks if the current element ('v[i]') is less than the pivot ('v[left]') or not. Then, accordingly swaps the lesser elements as in the line,

 swap(v, ++last, i);

from the location (last + 1) till where ever it increments to. So, the elements to the left of 'last' are less than pivot and the elements to the right are greater. I think you are missing another line, where we bring the pivot back to the middle which was at the location 'v[left]' during the execution of the algorithm. Then, the recursive calls play their roles. If you are looking for help with quicksort, this is a good place to start !

I hope my answer has helped you, if it did, let me know..! ☺

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!