快速排序

快速排序

最近简单复习了面试中经常会被问到的简单的问题,其中之一就是快排,平均时间复杂度为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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值