เทคนิคการเรียงลำดับแบบด่วนทำได้โดยแยกรายการออกเป็นสองส่วน ในขั้นต้น องค์ประกอบเดือยจะถูกเลือกโดยอัลกอริทึมการแบ่งพาร์ติชัน ส่วนด้านซ้ายของเดือยถือค่าที่น้อยกว่าเดือยและส่วนขวาถือค่าที่มากกว่า หลังจากแบ่งพาร์ติชัน แต่ละรายการแยกกันจะถูกแบ่งพาร์ติชันโดยใช้ขั้นตอนเดียวกัน
ความซับซ้อนของเทคนิค Quicksort
- ความซับซ้อนของเวลา:O(n log n) สำหรับกรณีที่ดีที่สุดและกรณีเฉลี่ย O(n^2) สำหรับกรณีที่เลวร้ายที่สุด
- ความซับซ้อนของอวกาศ:O(log n)
อินพุตและเอาต์พุต
Input: The unsorted list: 90 45 22 11 22 50 Output: Array before Sorting: 90 45 22 11 22 50 Array after Sorting: 11 22 22 45 50 90
อัลกอริทึม
พาร์ติชั่น(อาเรย์, ล่าง, บน)
อินพุต: อาร์เรย์ชุดข้อมูล ขอบเขตล่าง และขอบเขตบน
ผลลัพธ์: หมุนในตำแหน่งที่ถูกต้อง
Begin pivot := array[lower] start := lower and end := upper while start < end do while array[start] <= pivot AND start < end do start := start +1 done while array[end] > pivot do end := end – 1 done if start < end then swap array[start] with array[end] done array[lower] := array[end] array[end] := pivot return end End
quickSort(อาร์เรย์ ซ้าย ขวา
ป้อนข้อมูล - อาร์เรย์ของข้อมูลและขอบเขตล่างและบนของอาร์เรย์
ผลลัพธ์ − อาร์เรย์ที่เรียงลำดับ
Begin if lower < right then q = partition(arraym left, right) quickSort(array, left, q-1) quickSort(array, q+1, right) End
ตัวอย่าง
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
int partition(int *array, int lower, int upper) {
//Hoare partitioning technique to find correct location for pivot
int pivot, start, end;
pivot = array[lower]; //first element as pivot
start = lower; end = upper;
while(start < end) {
while(array[start] <= pivot && start<end) {
start++; //start pointer moves to right
}
while(array[end] > pivot) {
end--; //end pointer moves to left
}
if(start < end) {
swap(array[start], array[end]); //swap smaller and bigger element
}
}
array[lower] = array[end];
array[end] = pivot;
return end;
}
void quickSort(int *array, int left, int right) {
int q;
if(left < right) {
q = partition(array, left, right);
quickSort(array, left, q-1); //sort left sub-array
quickSort(array, q+1, right); //sort right sub-array
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
quickSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
} ผลลัพธ์
Enter the number of elements: 6 Enter elements: 90 45 22 11 22 50 Array before Sorting: 90 45 22 11 22 50 Array after Sorting: 11 22 22 45 50 90