Quick sort
1.Quick sort
2.Code
//Low and high specify indices which determin what portion of the list we're working on
public static int partition(int[] listToSort, int low, int high) {
//Choose a pivort to partition the list
int pivot = listToSort[low];
int l = low;
int h = high;
//The loop continues so long as the indices don't cross one another art the center
//Moving from either end of the list towards the center we compare the elements to the pivort
while (l < h){
//找出大於pivort的index
while (listToSort[l] <= pivort && l < h) {
l++;
}
//找出小於pivort的index
while (listToSort[h] > pivort) {
h--;
}
//Elements larger than the pivot are swapped to after the pivot
//and smaller elements move before the pivot
if (l > h) {
swap(listToSort, l, h);
}
}
//Swap the pivot element to the correct position in the list
swap(listToSort, low, h);
print(listToSort);
return h;
}3.Complexity
Last updated