教你一步一步写快速排序

本文详细介绍了一种高效的排序算法——快速排序。通过Java语言实现并分解为思考、编码、添加交换函数及测试四个步骤,帮助读者理解快速排序的核心原理及其具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速排序,顾名思义,在各种排序算法中,快速排序算法综合性能最为优异。所以掌握快速排序是一个程序员的基本功。
首先写出我的实现思路,本文采用Java语言,C/C++代码类似:
Step 0 : thinking
public class quickSortDemo{
    public static void main(String args[]){
        //define a test array
        //invoke the quickSort()
        //print the array after it was sorted
    }

    //function quickSort()
    public void quickSort(int array[],int left,int right){
        //do nothing if left >= right
        //invoke the partition()
        //recursive quickSort() the left parts and right parts
    } 

    //function partition()
    public int partition(int array[],int left,int right){
        //p<-get a number from array
        //put elements <= p to the left side
        //put elements >= p to the right side
        //put p in the middle slot which index id pivot
    }
}
Step 1 : encoding
 public int partition(int array[],int left,int right){
        //p<-get a number from array
        int p = array[left];
        int i = left;
        int j = 0;
        for(j=i+1;j<=right;j++){
        //put elements <= p to the left side 
        //put elements >= p to the right side
        if(p>array[j]){
                i++;
                swap(array,i,j);
            }
        }
        //put p in the middle slot which index id pivot
        swap(array,i,left);
        return i;
    }

    public void quickSort(int array[],int left,int right){
               //do nothing if left >= right
if(left<right){
               //invoke the partition()
int pivot = partition(array,left,right);
               //recursive quickSort() the left parts and right parts
quickSort(array,left,pivot-1);
quickSort(array,pivot+1,right);
}
}
Step 2 : add function swap()
//it's main function is to exchange number
public void swap(int array[],int i,int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Step 3 : test the class
public class Demo{
public static void main(String args[]){
int temp[] = {3,8,6,4,5,6,1,9,2,0,22,22,22,33,454,5,4,3333,22222};
new Demo().quickSort(temp,0,temp.length-1);
for(int i=0;i<temp.length;i++){
System.out.print(temp[i]+"、");
}
System.out.println();
}
























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值