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("
    ");
    }
    
  • 相关阅读:
    【中文分词】条件随机场CRF
    【中文分词】最大熵马尔可夫模型MEMM
    【中文分词】二阶隐马尔可夫模型2-HMM
    【中文分词】隐马尔可夫模型HMM
    Elasticsearch的CRUD:REST与Java API
    d3的比例尺和坐标轴
    webpack DllPlugin的用法
    webpack单独启动目录方法
    d3的常用方法和数据类型
    d3中的enter,exit,update概念
  • 原文地址:https://www.cnblogs.com/yldf/p/6249911.html
Copyright © 2011-2022 走看看