logo

Програма C++ для QuickSort

Подібний до Сортування злиттям алгоритм швидкого сортування є алгоритмом розділяй і володарюй. Спочатку він вибирає елемент як опорний елемент і розбиває заданий масив навколо вибраного опорного елемента. Існує багато різних версій QuickSort, які вибирають зведення різними способами.

  1. Завжди вибирайте перший елемент як опору (реалізовано нижче).
  2. Завжди вибирайте останній елемент як опору.
  3. Виберіть випадковий елемент як опору.
  4. Виберіть медіану як опору.

Ключовим процесом у QuickSort є процес partition(). Мета функції partition() полягає в тому, щоб отримати масив і елемент x масиву як опору, розмістити x у його правильній позиції в сортованому масиві, а потім розмістити всі менші елементи (менші за x) перед x і поставити усі більші елементи (більші за x) після x. Все це має бути зроблено за лінійний час, тобто великий O(n).
Псевдокод для рекурсивної функції QuickSort:



/* low -->Початковий індекс, високий --> Кінцевий індекс */ quickSort(arr[], low, high) { if (low Метод-1 : CPP // C++ Реалізація алгоритму швидкого сортування. #include з використанням простору імен std; int partition(int arr[], int start, int end) { int pivot = arr[start]; int count = 0; for (int i = start + 1; i<= end; i++) {  if (arr[i] <= pivot)  count++;  }  // Giving pivot element its correct position  int pivotIndex = start + count;  swap(arr[pivotIndex], arr[start]);  // Sorting left and right parts of the pivot element  int i = start, j = end;  while (i pivotIndex) {  while (arr[i] <= pivot) {  i++;  }  while (arr[j]>поворот) { j--;  } if (i pivotIndex) { swap(arr[i++], arr[j--]);  } } return pivotIndex; } void quickSort(int arr[], int start, int end) { // базовий випадок if (start>= end) return;  // розбиття масиву int p = partition(arr, start, end);  // Сортування лівої частини quickSort(arr, start, p - 1);  // Сортування правої частини quickSort(arr, p + 1, end); } int main() { int arr[] = { 9, 3, 4, 2, 1, 8 };  int n = 6;  швидке сортування (arr, 0, n - 1);  for (int i = 0; i cout<< arr[i] << ' ';  }  return 0; }  Output  1 2 3 4 8 9  Method-2 : This method’s space complexity is O(n). As we will take an extra array in partition function like in merge function of merge sort .  Algorithm explanation and steps of partition function:   Make a new array of size equal to given array. push all the smaller elements than pivotElement to the new array. Push pivotElement to new array now. finally, push all the greater elements than pivotElement to the new array. Now, copy the new array to the original array. Store the index of the pivotElement from the original array. Return this index.  After this, all the elements in the original array are in the order : smaller than pivotElement ->pivotElement -> більше ніж pivotElement. Часова складність: θ(nlogn). Просторова складність: O(n). C++ // додано Manish Sharma #include using namespace std; int partition(int* arr, int start, int end) { // припускаючи, що останній елемент є pivotElement int index = 0, pivotElement = arr[end], pivotIndex;  int* temp = новий int[кінець - початок + 1]; // створення масиву, розмір якого дорівнює поточному діапазону розділу... for (int i = start; i<= end; i++) // pushing all the elements in temp which are smaller than pivotElement  {  if(arr[i]   {  temp[index] = arr[i];  index++;  }  }  temp[index] = pivotElement; // pushing pivotElement in temp  index++;  for (int i = start; i // pushing all the elements in temp which are greater than pivotElement  {  if(arr[i]>pivotElement) { temp[index] = arr[i];  індекс++;  } } // усі елементи в тимчасовому масиві мають порядок: // крайні ліві елементи менші за pivotElement, а крайні праві елементи більші за pivotElement index = 0;  для (int i = початок; i<= end; i++) // copying all the elements to original array i.e arr  {   if(arr[i] == pivotElement)  {  // for getting pivot index in the original array.  // we need the pivotIndex value in the original and not in the temp array  pivotIndex = i;  }  arr[i] = temp[index];  index++;  }  return pivotIndex; // returning pivotIndex } void quickSort(int* arr, int start, int end) {   if(start   {   int partitionIndex = partition(arr, start, end); // for getting partition  quickSort(arr, start, partitionIndex - 1); // sorting left side array  quickSort(arr, partitionIndex + 1, end); // sorting right side array  }  return; } int main()  {   int size = 9;  int arr[size] = {5, 12, 7, 1, 13, 2 ,23, 11, 18};    cout << 'Unsorted array : ';  for (int i = 0; i   {  cout << arr[i] << ' ';  }  printf('
');  quickSort(arr, 0, size - 1);    cout << 'Sorted array : ';  for (int i = 0; i   {  cout << arr[i] << ' ';  }    return 0; }  Output  Unsorted array : 5 12 7 1 13 2 23 11 18 Sorted array : 1 2 5 7 11 12 13 18 23  Please refer complete article on QuickSort for more details!>