• 快速排序


    java版

    /************************************************

    File Name: QuickSort.java
    Author: lxm
    Created Time: 2016年04月27日 星期三 18时52分51秒
    **********************************************/

    public class QuickSort
    {
    private static final int N = 10;
    public static void main(String[] args)
    {
    int[] a = {6,1,2,7,9,3,4,5,10,8};
    quickSort(a,0,N-1);
    printArray(a);
    }

    public static void printArray(int[] a)
    {
        for(int item:a)
        {
            System.out.printf("%d	",item);
        }
        System.out.println();
    }
    public static void quickSort(int[] a, int low, int high)
    {
        if(low>=high)
        {
            return;
        }
        int key = partition(a,low,high);
        quickSort(a,0,key-1);
        quickSort(a,key+1,high);
    }
    
    public static int partition(int[] a,int low, int high)
    {
        int temp = a[low];
        while(low<high)
        {
            while(low<high && a[high]>=temp)
            {
                --high;
            }
            a[low] = a[high];
    
            while(low<high && a[low]<=temp)
            {
                ++low;
            }
            a[high] = a[low];
        }
    
        a[low] = temp;
    
        return low;
    }
    

    }

    ···

    C版本

    #include<stdio.h>
    #define N 10
    
    int partition(int* a,int low, int high);
    void quickSort(int* a,int low,int high);
    void printArray(int* a,int n);
    
    int main(void)
    {
        int a[N] = {6,1,2,7,9,3,4,5,10,8};
        quickSort(a,0,N-1);
    //  int k = partition(a,0,9);
    //  printf("%d
    ",k);
        printArray(a,N);
        return 0;
    }
    int partition(int* a,int low, int high)
    {
    
        int temp = a[low];
        while(low<high)
        {
            while(low<high && a[high]>=temp)
            {
                high--;
            }
            a[low] = a[high];
    
            while(low<high && a[low]<=temp)
            {
                ++low;
            }
            a[high] = a[low];
        }
        a[low] = temp;
    
        return low;
    }
    
    void quickSort(int* a,int low,int high)
    {
        if(low>=high)
        {
            return ;
        }
        int key = partition(a,low,high);
        quickSort(a,0,key-1);
        quickSort(a,key+1,high);
    }
    void printArray(int* a,int n)
    {
        int i;
        for(i=0;i<n;++i)
        {
            printf("%d	",a[i]);
        }
        printf("
    ");
    }
    
  • 相关阅读:
    day3 集合
    进度条
    day3 文件操作 seek tell 修改
    day3 函数
    同学满分代码,购物车。
    day2杂---三元运算 is
    模块sys os
    day2--列表/元组/字符串/字典
    一、Git配置
    四、TestNG 批量执行脚本Runner.xml
  • 原文地址:https://www.cnblogs.com/yldf/p/11900179.html
Copyright © 2020-2023  润新知