当前位置: 代码迷 >> 综合 >> 排序算法-快速排序(nlogn)
  详细解决方案

排序算法-快速排序(nlogn)

热度:25   发布时间:2023-12-24 22:55:31.0

快速排序

代码:

#include<iostream>
#include<string>using namespace std;
int Partition(int a[], int low, int high);
void QuickSort(int a[], int low, int high);int main()
{int buff[7] = { 5, 2, 1, 4, 9, 6, 0 };for (int i = 0; i < 7; i++)cout << buff[i] ;cout << endl;QuickSort(buff, 0, 6);for (int i = 0; i < 7; i++)cout << buff[i];cout << endl;return 0;
}int Partition(int a[], int low, int high)
{int x = a[high];//将输入数组的最后一个数作为主元,用它来对数组进行划分int i = low - 1;//i是最后一个小于主元的数的下标for (int j = low; j < high; j++)//遍历下标由low到high-1的数{if (a[j] < x)//如果数小于主元的话就将i向前挪动一个位置,并且交换j和i所分别指向的数{int temp;i++;temp = a[i];a[i] = a[j];a[j] = temp;}}//经历上面的循环之后下标为从low到i(包括i)的数就均为小于x的数了,现在将主元和i+1位置上面的数进行交换a[high] = a[i + 1];a[i + 1] = x;return i + 1;
}
void QuickSort(int a[], int low, int high)
{if (low < high){int q = Partition(a, low, high);QuickSort(a, low, q - 1);QuickSort(a, q + 1, high);}
}

结果:


  相关解决方案