Quick Sort Algorithm

快速排序算法实现代码:

//============================================================================
// Name        : QuickSort.cpp
// Author      : Danny
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

void swap(int a[], int i, int j) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

int position(int a[], int left, int right) {
    int pivot = left;
    int i = left;
    int j = right;
    while (i < j) {

        while (i < j && a[j] >= a[pivot]) {
            j--;
        }

        if (i < j && a[j] < a[pivot]) {
            swap(a, pivot, j);
            pivot = j;
        }

        while (i < j && a[i] <= a[pivot]) {
            i++;
        }
        if (i < j && a[i] > a[pivot]) {
            swap(a, pivot, i);
            pivot = i;
        }

    }
    return pivot;
}

void quickSort(int a[], int left, int right) {
    if (left >= right)
        return;
    int pos = position(a, left, right);
    quickSort(a, left, pos - 1);
    quickSort(a, pos + 1, right);

}

int main() {
    int a[8] = { 1,2,4,3,3,5,9,0};
    quickSort(a, 0, 7);
    for (int i = 0; i < 8; i++) {
        cout << a[i] << endl;
    }
    return 0;
}

 

Java实现代码:

排序类:

package algorithm;

public class SortAlgorithm {
    void quickSort(int a[], int left, int right) {
        if (left >= right)
            return;
        int pos = position(a, left, right);
        quickSort(a, left, pos - 1);
        quickSort(a, pos + 1, right);

    }
    
    void swap(int a[], int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    int position(int a[], int left, int right) {
        int pivot = left;
        int i = left;
        int j = right;
        while (i < j) {

            while (i < j && a[j] >= a[pivot]) {
                j--;
            }

            if (i < j && a[j] < a[pivot]) {
                swap(a, pivot, j);
                pivot = j;
            }

            while (i < j && a[i] <= a[pivot]) {
                i++;
            }
            if (i < j && a[i] > a[pivot]) {
                swap(a, pivot, i);
                pivot = i;
            }

        }
        return pivot;
    }
    
}

主方法类:

package algorithm;

public class QuickSort {

    public static SortAlgorithm sa;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        sa=new SortAlgorithm();
        int[] a={4,2,1,6,3};
        sa.quickSort(a, 0, 4);
        for(int i:a){
            System.out.println(i);
        }    
    }    
}

 

posted @ 2015-05-24 01:31  CHEN0958  阅读(197)  评论(0编辑  收藏  举报