zoukankan      html  css  js  c++  java
  • 快速排序

    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("
    ");
    }
    
  • 相关阅读:
    HDU 5360 Hiking(优先队列)2015 Multi-University Training Contest 6
    多区域显示(6)-版面布局
    静态变量和成员变量的区别 && 成员变量和局部变量的区别
    java基础学习_面向对象(上)02_day07总结
    java基础学习_面向对象(上)01_day07总结
    面向对象的概述
    面向对象思想的引入
    Failed to create the Java Virtual Machine(zt)
    eclipse web开发Server配置
    javamail接收邮件(zt)
  • 原文地址:https://www.cnblogs.com/yldf/p/11900179.html
Copyright © 2011-2022 走看看