quicksort算法_QuickSort算法–用C,Java,Python实现

quicksort算法

介绍 (Introduction)

Quicksort algorithm is one of the fastest internal sorting algorithms and today we are going to discuss this topic.

Quicksort算法是最快的内部排序算法之一,今天我们将讨论这个主题。

It is mainly based on the following three main strategies:

它主要基于以下三个主要策略:

  1. Split or Partition: Select a random element called pivot from the given sequence of elements to be sorted. Suppose the element is X, where X is any number. Now split the list into two small arrays or lists Y and Z such that, all elements in Y are smaller than X whereas all elements in Z are larger than X,

    拆分或分区 :从要排序的给定元素序列中选择一个随机元素,称为数据透视。 假设元素是X,其中X是任何数字。 现在将列表分成两个小数组或列表Y和Z,这样,Y中的所有元素都小于X,而Z中的所有元素都大于X,
  2. Sort the sub-arrays,

    排序子数组,
  3. Merge(join or concatenate) the sorted sub-arrays.

    合并合并或连接)已排序的子数组。

The split divides the arrays into two smaller arrays. When these sub-arrays are ultimately sorted recursively using quicksort these sub-arrays are called conquered. Therefore, quicksort is based on divide and conquer algorithm.

拆分将数组分成两个较小的数组。 当最终使用quicksort对这些子数组进行递归排序时,这些子数组称为conquered 。 因此,快速排序基于分而治之算法。

快速排序算法 (The Quick Sort Algorithm)

Suppose there are N elements as a[0], a[1], …, a[N-1]. The steps for using the quick sort algorithm are given below,

假设有N个元素,分别为a [0],a [1],…,a [N-1]。 下面给出了使用快速排序算法的步骤,

#1: Select any element as a pivot. For example, we select the first element here. It’ll help to split the array into two parts.

#1:选择任何元素作为枢轴 。 例如,我们在这里选择第一个元素。 这将有助于将数组分为两部分。


PIVOT = a[ FIRST ] //pivot selected,FIRST=0 here

#2: Initialize two pointers i and j as,

2:将两个指针ij初始化为


i = FIRST + 1 //First index of the array
j = LAST //Last index of array

#3: Now we increase the value of i until we locate an element that is greater than the pivot element,

3 :现在,我们增加i的值,直到找到一个大于数据透视元素的元素为止,


WHILE i<=j and a[i]<= PIVOT
    i=i+1

#4: We decrease the value of j until we find a value less than the pivot element,

4:我们减小j的值,直到找到小于枢轴元素的值,


WHILE j<=j and a[j]>= PIVOT
    j=j-1

#5: If i<j interchange a[i] and a[j].

#5:如果i <j,则互换a [i]和a [j]。

#6: Repeat Steps 2 to 4 until i>j,

6:重复步骤2到4,直到i> j

#7: Interchange the selected pivot and a[j],

#7:将所选的枢轴和a [j]互换,

#8: And finally recursively call this Quicksort for the two sub-arrays hence created at the two sides of the pivot element.

8 :最后为在枢轴元素两侧创建的两个子数组递归调用此Quicksort。

通过示例了解算法 (Understanding the Algorithm with an Example)

Now, let us understand how the algorithm works using a simple example.

现在,让我们使用一个简单的例子来了解算法的工作原理。

We have considered an array having values 50, 30, 10, 90, 80, 20, 40, 60 as shown in figure 1. At first, we select a pivot element which in our case is the first element, 50.

我们考虑具有如图1.在第一阵列值50,30,10,90,80,20,40,60中,我们选择一个枢轴元件,其在我们的例子中是第一要素,50。

Fig123
Quicksort Algorithm
快速排序算法

Then we initialize i and j pointers as shown in figure 2 pointing on 30 and 60 respectively. Hence we move the i pointer towards the right until the element is greater than the pivot one. Which in our case we get at index 3, that is the value 90.

然后我们初始化ij指针,如图2所示,分别指向30和60。 因此,我们将i指针向右移动,直到元素大于枢轴元素。 在我们的情况下,我们得到的是索引3,即值90

Fig456 1
Quicksort Algorithm
快速排序算法

Similarly, j is moved towards the left until it finds a value smaller than the pivot, which we get at index 6 that is a value of 40. At this point in figure 6, we can see we have got both i and j values. Finally, we swap the corresponding values and get to a position shown in figure 7.

类似地,j向左移动,直到找到小于枢轴的值,该值在索引6处为40 。 在图6的这一点上,我们可以看到我们同时获得了i和j值。 最后,我们交换相应的值并到达图7所示的位置。

Fig789
Quicksort Algorithm
快速排序算法

Then we again go through the i and j index searching and hence get to figure 9, where both our pointers, i and j stand at 4th and 5th index.

然后,我们再次进行i和j索引搜索,从而转到图9 ,其中我们的指针i和j都位于第4和第5个索引。

Similar to the previous case, we swap the corresponding values at ith and jth positions. So after this, we need to move the pointer i towards the right and j towards the left. Since 20<50, so we need to increase i by 1 towards the right. As 80>50, we stop moving i further. As shown in figure 10 and 11.

与前面的情况类似,我们在ith和jth位置交换相应的值。 因此,在此之后,我们需要将指针i向右移动,将j向左移动。 由于20 <50,因此我们需要将i向右增加1。 随着80> 50,我们不再移动i。 如图1011所示

Fig101112
Quicksort Algorithm
快速排序算法

Then we start moving j towards the left. As 20<50, j is decreased by 1 and now stands at the 4th index as shown in figure 12. From the above condition, it is clear that i crosses j. Thus we stop at the point where j<i. Therefore the position of j is the split point.

然后我们开始将j向左移动。 当20 <50时,j减小1,现在位于第4个索引,如图12所示。从上述条件可以清楚地看出,i与j交叉。 因此,我们在j <i处停止。 因此,j的位置是分割点。

Hence we swap the pivot and the value at index j points at giving us the array as in figure 13.

因此,我们交换枢轴和索引j点的值,得到如图13所示的数组

Fig13
Quicksort Algorithm
快速排序算法

After this, we have to apply the same method for the sub-arrays to the left and right of the pivot element, 50. By this divide and conquer method, finally, we will get our sorted array.

此后,我们必须在枢轴元素50的左侧和右侧对子数组应用相同的方法。 最后,通过这种分而治之的方法,我们将获得排序后的数组。

实现QuickSort算法 (Implementing the QuickSort Algorithm )

1. C语言中的QuickSort算法 (1. QuickSort Algorithm in C)


#include<stdio.h>
void quicksort(int a[25],int first,int last)
{
   int i, j, pivot, temp;

   if(first<last){
      pivot=first;
      i=first;
      j=last;

      while(i<j){
         while(a[i]<=a[pivot] && i<last)
            i++;
         while(a[j]>a[pivot])
            j--;
         if(i<j){
            temp=a[i];
            a[i]=a[j];
            a[j]=temp;
         }
      }

      temp=a[pivot];
      a[pivot]=a[j];
      a[j]=temp;
      quicksort(a,first,j-1);
      quicksort(a,j+1,last);

   }
}

int main()
{
   int i, n, a[25];

   printf("Enter total no.of elements: ");
   scanf("%d",&n);

   printf("Enter the elements: ");
   for(i=0;i<n;i++)
      scanf("%d",&a[i]);

   quicksort(a,0,n-1);

   printf("Sorted Array: ");
   for(i=0;i<n;i++)
      printf(" %d",a[i]);

   return 0;
}

Output:

输出

Quicksort In C
Quicksort In C
C中的快速排序

2. Java中的QuickSort算法 (2. QuickSort Algorithm in Java)


public class Quicksort
{
    int position(int a[], int first, int last) 
    { 
        int pivot = a[last];  
        int i = (first-1); 
        for (int j=first; j<last; j++) 
        { 
            if (a[j] <= pivot) 
            { 
                i++;  
                int temp = a[i]; 
                a[i] = a[j]; 
                a[j] = temp; 
            } 
        } 
   
        int temp = a[i+1]; 
        a[i+1] = a[last]; 
        a[last] = temp; 
  
        return i+1; 
    } 
    
    void Qsort(int a[], int first, int last) 
    { 
        if (first < last) 
        { 
            int p = position(a, first, last);  
            Qsort(a, first, p-1); 
            Qsort(a, p+1, last); 
        } 
    } 
  
    public static void main(String args[]) 
    { 
        int a[] = { 50, 30, 10, 90, 80, 20, 40, 60}; 
        int n = a.length; 
        Quicksort ob = new Quicksort(); 
        ob.Qsort(a, 0, n-1); 
  

        System.out.println("sorted array:"); 
        for (int i=0; i<n; i++) 
            System.out.print(a[i]+" "); 
        System.out.println();
    } 
}

Output

输出量

Quicksort In Java
Quicksort In Java
Java快速排序

3. Python中的QuickSort算法 (3. QuickSort Algorithm in Python)


def quicksort(Mylist):
    n=len(Mylist)
    Rec_quicksort(Mylist, 0, n-1)

def Rec_quicksort(Mylist, first, last):
    if first<last:
        pos=position(Mylist, first, last)
        Rec_quicksort(Mylist, first, pos-1)
        Rec_quicksort(Mylist, pos+1, last)

def position(Mylist, first, last):
    pivot=Mylist[first]
    i=first
    j=last

    while i<j:
        while i<=j and Mylist[i]<=pivot:
            i=i+1
        while pivot<Mylist[j]:
            j=j-1
        if i<j:
            temp=Mylist[i]
            Mylist[i]=Mylist[j]
            Mylist[j]=temp

    temp=Mylist[first]
    Mylist[first]=Mylist[j]
    Mylist[j]=temp
    return j

Mylist=[ 50, 30, 10, 90, 80, 20, 40, 60 ]
print("Given list:",Mylist)

quicksort(Mylist)
print("After sorting list is:",Mylist)

Output:

输出

Quicksort In Python
Quicksort In Python
Python快速排序

QuickSort算法的时空复杂度 (Time and Space Complexity of QuickSort Algorithm)

空间复杂度 (Space complexity)

The space complexity of Quicksort algorithm is given by O(log(n)).

Quicksort算法的空间复杂度由O(log(n))给出。

时间复杂度 (Time complexity)

The time complexity of Quicksort algorithm is given by,

Quicksort算法的时间复杂度由下式给出:

  • O(n log(n)) for best case,

    O(n log(n))为最佳情况,
  • O(n log(n)) for the average case,

    O(n log(n))平均情况
  • And O(n^2) for the worst-case scenario.

    O(n ^ 2)在最坏的情况下。

结论 (Conclusion)

Finally, we hope you have a very good understanding of the Quicksort algorithm. We implemented the same in C, Java, and Python to help programmers comfortable with either of the languages understand this algorithm better. Let us know if you have any questions about this topic in the comments.

最后,我们希望您对Quicksort算法有很好的了解。 我们用C,JavaPython实现了相同的功能以帮助程序员熟悉这两种语言,从而更好地理解该算法。 如果您在评论中对此主题有任何疑问,请告诉我们。

参考资料 (References)

翻译自: https://www.journaldev.com/37033/quicksort-algorithm-in-c-java-python

quicksort算法

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当谈到快速排序算法时,有多种变体和优化方法可供选择。以下是几个常见的快速排序算法实现示例,使用 Python 编程语言: 1. 基本快速排序算法: ```python def quicksort_basic(arr): if len(arr) <= 1: return arr pivot = arr[len(arr) // 2] less, equal, greater = [], [], [] for num in arr: if num < pivot: less.append(num) elif num == pivot: equal.append(num) else: greater.append(num) return quicksort_basic(less) + equal + quicksort_basic(greater) ``` 2. 优化快速排序算法(使用随机选择枢轴元素): ```python import random def quicksort_optimized(arr): if len(arr) <= 1: return arr pivot = random.choice(arr) less, equal, greater = [], [], [] for num in arr: if num < pivot: less.append(num) elif num == pivot: equal.append(num) else: greater.append(num) return quicksort_optimized(less) + equal + quicksort_optimized(greater) ``` 3. 优化快速排序算法(使用三数取中法选择枢轴元素): ```python def quicksort_median_of_three(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 pivot = sorted([arr[0], arr[mid], arr[-1]])[1] less, equal, greater = [], [], [] for num in arr: if num < pivot: less.append(num) elif num == pivot: equal.append(num) else: greater.append(num) return quicksort_median_of_three(less) + equal + quicksort_median_of_three(greater) ``` 以上是一些常见的快速排序算法实现示例,你可以根据自己的需要选择适合的算法快速排序算法的时间复杂度通常为 O(nlogn),在大多数情况下表现良好。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值