快速排序
最近简单复习了面试中经常会被问到的简单的问题,其中之一就是快排,平均时间复杂度为nlog(2`n),是不稳定排序算法。
该算法可以简单描述为,第一趟将第一个元素设置为交换元素,然后从后向前找比交换元素小的元素,将其与交换元素交换,接着从前向后找比交换元素大的元素,将其再与交换元素交换,直到这一趟元素排完,接着使用递归的方法,将其前半部分后后办部分进行同样的遍历。具体算法看代码:
Java
public class Main {
public static void Qsort(int[] arrays, int low, int high) {
int l = low;
int h = high;
while (low < high) {
int current_num = arrays[low];
while (low < high && arrays[high] >= current_num) {
high--;
}
if (low < high) {
int temp = arrays[low];
arrays[low] = arrays[high];
arrays[high] = temp;
low++;
}
while (low < high && arrays[low] <= current_num) {
low++;
}
if (low < high) {
int temp = arrays[low];
arrays[low] = arrays[high];
arrays[high] = temp;
high--;
}
}
if (low > l)
Qsort(arrays, l, low - 1);
if (high < h)
Qsort(arrays, low + 1, h);
}
public static void main(String[] args) {
int[] arrays = { 2, 3, 5, 1, 9, 55, 43, 2, 2, 22, 34, 5, 6, 77, 88 };
Qsort(arrays, 0, arrays.length - 1);
for (int i = 0; i < arrays.length; i++) {
System.out.print(arrays[i] + " ");
}
}
}
C++
#include <iostream>
using namespace std;
void Qsort(int arr[],int low,int high)
{
int l=low;
int h=high;
while(l<h)
{
int current_num=arr[l];
while(l<h&&arr[h]>=current_num)
{
h--;
}
if(l<h)
{
int temp=arr[l];
arr[l]=arr[h];
arr[h]=temp;
l++;
}
while(l<h&&arr[l]<=current_num)
{
l++;
}
if(l<h)
{
int temp=arr[l];
arr[l]=arr[h];
arr[h]=temp;
h--;
}
}
if(low<l)Qsort(arr,low,l-1);
if(high>h)Qsort(arr,h+1,high);
}
int main()
{
int arr[]= {6,32,33,98,11,33,44,55,7,8,99,90};
Qsort(arr,0,sizeof(arr)/sizeof(int)-1);
for(int i=0; i<sizeof(arr)/sizeof(int); i++)
{
cout<<arr[i]<<endl;
}
return 0;
}