dzungchaos

CTDL&TT: Quick Sort

Jul 5th, 2020
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include<stdio.h>
  2.  
  3.  
  4. void swap(int &a, int &b)
  5. {
  6.     int t = a;
  7.     a = b;
  8.     b = t;
  9. }
  10.  
  11.  
  12. int partition (int arr[], int low, int high)
  13. {
  14.     int pivot = arr[high];    // pivot
  15.     int left = low;
  16.     int right = high - 1;
  17.     while(true){
  18.         while(left <= right && arr[left] < pivot) left++;
  19.         while(right >= left && arr[right] > pivot) right--;
  20.         if (left >= right) break;
  21.         swap(arr[left], arr[right]);
  22.         left++;
  23.         right--;
  24.     }
  25.     swap(arr[left], arr[high]);
  26.     return left;
  27. }
  28.  
  29. /* Hàm thực hiện giải thuật quick sort */
  30. void quickSort(int arr[], int low, int high)
  31. {
  32.     if (low < high)
  33.     {
  34.         /* pi là chỉ số nơi phần tử này đã đứng đúng vị trí
  35.          và là phần tử chia mảng làm 2 mảng con trái & phải */
  36.         int pi = partition(arr, low, high);
  37.  
  38.         // Gọi đệ quy sắp xếp 2 mảng con trái và phải
  39.         quickSort(arr, low, pi - 1);
  40.         quickSort(arr, pi + 1, high);
  41.     }
  42. }
  43.  
  44. /* Hàm xuất mảng */
  45. void printArray(int arr[], int size)
  46. {
  47.     int i;
  48.     for (i=0; i < size; i++)
  49.         printf("%d ", arr[i]);
  50.     printf("\n");
  51. }
  52.  
  53.  
  54. int main()
  55. {
  56.     int arr[] = {10, 80, 30, 90, 40, 50, 70};
  57.     int n = sizeof(arr)/sizeof(arr[0]);
  58.     quickSort(arr, 0, n-1);
  59.     printf("Sorted array: \n");
  60.     printArray(arr, n);
  61.     return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment