C语言版本:
/*快速排序 2012.2.25*/
#include <stdio.h>
int partion(int a[],int low,int high) //返回枢轴位置
{
int i=low;
int j=high;
int pivot=a[low];
while(i<j)
{
while(i<j&&a[j]>=pivot)
{
--j;
}
a[i]=a[j];
while(i<j&&a[i]<=pivot)
{
++i;
}
a[j]=a[i];
}
a[i]=pivot;
return i;
}
void quickSort(int a[],int low,int high) //快速排序
{
if(low<high)
{
int pivotpos=partion(a,low,high);
quickSort(a,low,pivotpos-1);
quickSort(a,pivotpos+1,high);
}
}
int main(int argc, char *argv[])
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
int *a=new int[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
quickSort(a,0,n-1);
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
return 0;
}
Java 版本:
package algorithm.sort;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import time.Timing;
public class QuickSort{
public <T extends Comparable<T>> void quickSort1(ArrayList<T> arr,int l,int u){
if (l>=u) {
return;
}
int m=l;
for (int i = l+1; i <= u; i++) {
if (arr.get(i).compareTo(arr.get(l))<0) {
Collections.swap(arr, ++m, i);
}
}
Collections.swap(arr, l, m);
quickSort1(arr, l, m-1);
quickSort1(arr, m+1, u);
}
public <T extends Comparable<T>> void quickSort2(ArrayList<T> arr,int l,int u){
if (l>=u) {
return;
}
T temp=arr.get(l); int i=l; int j=u;
while(i<j){
for (; i < j && arr.get(j).compareTo(temp)>=0; j--);
for (; i < j && arr.get(i).compareTo(temp)<=0; i++);
if (i>j) {
break;
}
Collections.swap(arr, i, j);
}
Collections.swap(arr, j, l);
quickSort2(arr, l, j-1);
quickSort2(arr, j+1, u);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> arr=new ArrayList<Integer>();
QuickSort qs=new QuickSort();
try {
FileOutputStream fos = new FileOutputStream("D:\\workspace\\DataStructures\\src\\algorithm\\sort\\rank_data.txt");
OutputStreamWriter w = new OutputStreamWriter(fos, "UTF-8");
InputStreamReader fr = new InputStreamReader(
new FileInputStream("D:\\workspace\\DataStructures\\src\\algorithm\\sort\\random_data.txt"));
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
arr.add(Integer.parseInt(line));
}
Timing sorTimer = new Timing();
double timeInSec;
sorTimer.start();
qs.quickSort2(arr, 0, arr.size() - 1);
timeInSec = sorTimer.stop();
for (int i : arr) {
w.write(i + "\n");
}
System.out.println(timeInSec);
br.close();
fr.close();
w.close();
fos.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}