C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序

本文将探讨如何使用随机枢轴实现快速排序。在快速排序中,我们首先对数组进行原地分割,使得枢轴元素左侧的所有元素都小于枢轴元素,而右侧的所有元素都大于枢轴元素。然后,我们递归地对左右两个子数组执行相同的分割过程。 与归并排序

不同,快速排序不需要合并两个已排序的数组。因此,快速排序所需的辅助空间比归并排序更少,这也是它通常优于归并排序的原因。使用随机生成的枢轴可以进一步降低快速排序的时间复杂度。

我们已经讨论了两种流行的数组划分方法------霍尔划分方案和洛穆托划分方案

建议读者已经阅读过这篇文章,或者知道如何使用这两种划分方案中的任何一种来实现快速排序。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

基于 Lomuto 分区的随机枢轴算法

partition(arr\[\], lo, hi)

pivot = arrhi

i = lo // 用于交换的位置

for j := lo to hi -- 1 do

if arrj <= pivot then

swap arri with arrj

i = i + 1

swap arri with arrhi

return i

partition_r(arr\[\], lo, hi)

r = Random Number from lo to hi

Swap arrr and arrhi

return partition(arr, lo, hi)

quicksort(arr\[\], lo, hi)

if lo < hi

p = partition_r(arr, lo, hi)

quicksort(arr, lo , p-1)

quicksort(arr, p+1, hi)

++使用 Lomuto 分区法实现:++

// C# program to illustrate

// Randomised Quick sort

using System;

class RandomizedQsort

{

/* This function takes last element as pivot,

places the pivot element at its correct

position in sorted array, and places all

smaller (smaller than pivot) to left of

pivot and all greater elements to right

of pivot */

static int partition(int\[\] arr, int low, int high)

{

// pivot is chosen randomly

random(arr, low, high);

int pivot = arrhigh;

int i = (low-1); // index of smaller element

for (int j = low; j < high; j++)

{

// If current element is smaller than or

// equal to pivot

if (arrj < pivot)

{

i++;

// swap arri and arrj

int tempp = arri;

arri = arrj;

arrj = tempp;

}

}

// swap arri+1 and arrhigh (or pivot)

int tempp2 = arri + 1;

arri + 1 = arrhigh;

arrhigh = tempp2;

return i + 1;

}

// This Function helps in calculating

// random numbers between low(inclusive)

// and high(inclusive)

static int random(int\[\] arr, int low, int high)

{

Random rand = new Random();

int pivot = rand.Next() % (high - low) + low;

int tempp1 = arrpivot;

arrpivot = arrhigh;

arrhigh = tempp1;

return partition(arr, low, high);

}

/* The main function that implements Quicksort()

arr\[\] --> Array to be sorted,

low --> Starting index,

high --> Ending index */

static void sort(int\[\] arr, int low, int high)

{

if (low < high)

{

/* pi is partitioning index, arrpi is

now at right place */

int pi = partition(arr, low, high);

// Recursively sort elements before

// partition and after partition

sort(arr, low, pi - 1);

sort(arr, pi + 1, high);

}

}

/* A utility function to print array of size n */

static void printArray(int\[\] arr)

{

int n = arr.Length;

for (int i = 0; i < n; ++i)

Console.Write(arri + " ");

Console.WriteLine();

}

// Driver Code

static public void Main ()

{

int\[\] arr = {10, 7, 8, 9, 1, 5};

int n = arr.Length;

sort(arr, 0, n-1);

Console.WriteLine("sorted array");

printArray(arr);

}

}

// This code is contributed by shubhamsingh10

输出

复制代码
已排序数组:
1 5 7 8 9 10

时间复杂度: O(N*N)
辅助空间: O(N) // 由于递归调用栈

++使用霍尔分区法的随机枢轴算法++

partition(arr\[\], lo, hi)

pivot = arrlo

i = lo - 1 // Initialize left index

j = hi + 1 // Initialize right index

while(True)

// Find a value in left side greater than pivot

do

i = i + 1

while arri < pivot

// Find a value in right side smaller than pivot

do

j = j - 1

while arrj > pivot

if i >= j then

return j

else

swap arri with arrj

end while

partition_r(arr\[\], lo, hi)

r = Random number from lo to hi

Swap arrr and arrlo

return partition(arr, lo, hi)

quicksort(arr\[\], lo, hi)

if lo < hi

p = partition_r(arr, lo, hi)

quicksort(arr, lo, p)

quicksort(arr, p+1, hi)

++使用霍尔分区法的实现:++

// C# implementation of QuickSort

// using Hoare's partition scheme

using System;

public class GFG {

// Driver Code

public static void Main()

{

int\[\] arr = { 10, 7, 8, 9, 1, 5 };

int n = arr.Length;

quickSort(arr, 0, n - 1);

Console.WriteLine("Sorted array: ");

printArray(arr, n);

}

// This function takes last element as

// pivot, places the pivot element at

// its correct position in sorted

// array, and places all smaller

// (smaller than pivot) to left of pivot

// and all greater elements to right

public static int partition(int\[\] arr, int low,

int high)

{

int pivot = arrlow;

int i = low - 1, j = high + 1;

// Find leftmost element greater than

// or equal to pivot

while (true) {

do {

i++;

} while (arri < pivot);

// Find rightmost element smaller than

// or equal to pivot

do {

j--;

} while (arrj > pivot);

// If two pointers met

if (i >= j)

return j;

swap(arr, i, j);

}

}

// Generates Random Pivot, swaps pivot with

// end element and calls the partition function

// In Hoare partition the low element is selected

// as first pivot

public static int partition_r(int\[\] arr, int low,

int high)

{

// Generate a random number in between

// low .. high

Random rnd = new Random();

int random = low + rnd.Next(high - low);

// Swap Arandom with Ahigh

swap(arr, random, low);

return partition(arr, low, high);

}

// The main function that implements QuickSort

// arr\[\] --> Array to be sorted,

// low --> Starting index,

// high --> Ending index

public static void quickSort(int\[\] arr, int low,

int high)

{

if (low < high) {

// pi is partitioning index,

// arrp is now at right place

int pi = partition_r(arr, low, high);

// Separately sort elements before

// partition and after partition

quickSort(arr, low, pi);

quickSort(arr, pi + 1, high);

}

}

// Function to print an array

public static void printArray(int\[\] arr, int n)

{

for (int i = 0; i < n; i++)

Console.Write("{0} ", arri);

Console.Write("\n");

}

public static void swap(int\[\] arr, int i, int j)

{

int temp = arri;

arri = arrj;

arrj = temp;

}

}

输出

复制代码
已排序数组:
1 5 7 8 9 10

时间复杂度: O(N*N)
辅助空间: O(N) // 由于递归调用栈

使用 generateRandomPivot 函数实现:

这里提供了一种不使用 Hoare 和 Lomuto 分区方案的实现方法。

使用随机枢轴而不进行分区实现快速排序:

using System;

class Program {

// Function to swap two elements

static void Swap(int\[\] arr, int i, int j) {

int temp = arri;

arri = arrj;

arrj = temp;

}

// Function to generate a random pivot index

static int GenerateRandomPivot(int low, int high) {

Random random = new Random();

return low + random.Next(high - low + 1);

}

// Function to perform QuickSort

static void QuickSort(int\[\] arr, int low, int high) {

if (low < high) {

int pivotIndex = GenerateRandomPivot(low, high);

int pivotValue = arrpivotIndex;

// Swap the pivot element with the last element

Swap(arr, pivotIndex, high);

int i = low - 1;

for (int j = low; j < high; j++) {

if (arrj < pivotValue) {

i++;

Swap(arr, i, j);

}

}

// Swap the pivot element back to its final position

Swap(arr, i+1, high);

// Recursively sort the left and right subarrays

QuickSort(arr, low, i);

QuickSort(arr, i+2, high);

}

}

static void Main() {

int\[\] arr = {5, 2, 7, 3, 1, 6, 4, 8};

int n = arr.Length;

Console.Write("Original array: ");

for (int i = 0; i < n; i++) {

Console.Write(arri + " ");

}

QuickSort(arr, 0, n-1);

Console.Write("\nSorted array: ");

for (int i = 0; i < n; i++) {

Console.Write(arri + " ");

}

}

}

输出

复制代码
原始数组:5 2 7 3 1 6 4 8
排序后数组:1 2 3 4 5 6 7 8

随机快速排序分析

笔记

  • 使用随机枢轴,我们将预期或平均时间复杂度改进为 O (N log N)。最坏情况下的复杂度仍然是 O ( N^2 )。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
得物技术1 小时前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六4 小时前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程
胡萝卜术5 小时前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
Asize6 小时前
初识DFS 与 BFS:递归、队列与图遍历
算法
罗西的思考19 小时前
机器人 / 强化学习】HIL-SERL:人类在环驱动的具身智能进化框架
人工智能·算法·机器学习
CSharp精选营1 天前
关系型 vs 非关系型:从原理到选型,一文搞定数据库核心分类
数据结构·nosql·关系型数据库·非关系型数据库·技术选型
美团技术团队1 天前
LongCat 开源 VitaBench 2.0:长期动态智能体基准新标杆
人工智能·算法
To_OC2 天前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC2 天前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl