📅  最后修改于: 2020-10-15 03:10:18             🧑  作者: Mango
快速排序是广泛使用的排序算法,该算法在平均情况下对n个元素的数组进行n log n个比较。该算法遵循分而治之的方法。该算法以以下方式处理数组。
确保a [loc]小于a [right]。
Complexity | Best Case | Average Case | Worst Case |
---|---|---|---|
Time Complexity | O(n) for 3 way partition or O(n log n) simple partition | O(n log n) | O(n2) |
Space Complexity | O(log n) |
分区(ARR,BEG,END,LOC)
QUICK_SORT(ARR,BEG,END)
#include
int partition(int a[], int beg, int end);
void quickSort(int a[], int beg, int end);
void main()
{
int i;
int arr[10]={90,23,101,45,65,23,67,89,34,23};
quickSort(arr, 0, 9);
printf("\n The sorted array is: \n");
for(i=0;i<10;i++)
printf(" %d\t", arr[i]);
}
int partition(int a[], int beg, int end)
{
int left, right, temp, loc, flag;
loc = left = beg;
right = end;
flag = 0;
while(flag != 1)
{
while((a[loc] <= a[right]) && (loc!=right))
right--;
if(loc==right)
flag =1;
else if(a[loc]>a[right])
{
temp = a[loc];
a[loc] = a[right];
a[right] = temp;
loc = right;
}
if(flag!=1)
{
while((a[loc] >= a[left]) && (loc!=left))
left++;
if(loc==left)
flag =1;
else if(a[loc]
输出:
The sorted array is:
23
23
23
34
45
65
67
89
90
101
public class QuickSort {
public static void main(String[] args) {
int i;
int[] arr={90,23,101,45,65,23,67,89,34,23};
quickSort(arr, 0, 9);
System.out.println("\n The sorted array is: \n");
for(i=0;i<10;i++)
System.out.println(arr[i]);
}
public static int partition(int a[], int beg, int end)
{
int left, right, temp, loc, flag;
loc = left = beg;
right = end;
flag = 0;
while(flag != 1)
{
while((a[loc] <= a[right]) && (loc!=right))
right--;
if(loc==right)
flag =1;
elseif(a[loc]>a[right])
{
temp = a[loc];
a[loc] = a[right];
a[right] = temp;
loc = right;
}
if(flag!=1)
{
while((a[loc] >= a[left]) && (loc!=left))
left++;
if(loc==left)
flag =1;
elseif(a[loc]
输出:
The sorted array is:
23
23
23
34
45
65
67
89
90
101
using System;
public class QueueSort{
public static void Main() {
int i;
int[] arr={90,23,101,45,65,23,67,89,34,23};
quickSort(arr, 0, 9);
Console.WriteLine("\n The sorted array is: \n");
for(i=0;i<10;i++)
Console.WriteLine(arr[i]);
}
public static int partition(int[] a, int beg, int end)
{
int left, right, temp, loc, flag;
loc = left = beg;
right = end;
flag = 0;
while(flag != 1)
{
while((a[loc] <= a[right]) && (loc!=right))
right--;
if(loc==right)
flag =1;
else if(a[loc]>a[right])
{
temp = a[loc];
a[loc] = a[right];
a[right] = temp;
loc = right;
}
if(flag!=1)
{
while((a[loc] >= a[left]) && (loc!=left))
left++;
if(loc==left)
flag =1;
else if(a[loc]
输出:
The sorted array is:
23
23
23
34
45
65
67
89
90
101