码迷,mamicode.com
首页 > 其他好文 > 详细

Quick Sort Algorithm

时间:2015-05-24 06:29:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

快速排序算法实现代码:

//============================================================================
// 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);
        }    
    }    
}

 

Quick Sort Algorithm

标签:

原文地址:http://www.cnblogs.com/chen0958/p/4525289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!