快速排序之算法导论实现
2014-07-07 23:53
411 查看
#include <iostream> using namespace std; int partition(int *a,int p,int r) { int x=a[r]; int i=p-1;//note i important which is used for //storage the number smaller than flag x=a[r] for (int j=p;j<r;j++) { if (a[j]<x)// if a[j] smaller than x=a[r], //exchange a[i+1] and a[j] { i++; int t=a[j]; a[j]=a[i]; a[i]=t; } } int t=a[i+1];// i+1 is the a[r] final position // exchange a[r] and a[i+1] a[i+1]=a[r]; a[r]=t; return i+1; //return the a[r] final position i+1 } void quicksort(int *a,int p,int r) { if (p<r)//the position lower than the higher { int q=partition(a,p,r);//q is the a[r] final position // depart the arry[p...q-1] and arry[q+1...r] quicksort(a,p,q-1); quicksort(a,q+1,r); } } int main() { int arry[]={3,2,1,4,5,6,9,8,7,0}; quicksort(arry,0,9); for (int i=0;i<10;i++) cout<<arry[i]<<" "; cout<<endl; }
import java.util.Scanner; public class QuickSort { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner=new Scanner(System.in); int n=Integer.parseInt(scanner.next()); int a[]=new int ; for (int i = 0; i < a.length; i++) { a[i]=Integer.parseInt(scanner.next()); } quickSort(a, 0, n-1); for (int i = 0; i < a.length; i++) { System.out.print(a[i]+" "); } } public static void quickSort(int a[], int p, int e) { if (p<e) { int q=partion(a, p, e); quickSort(a, p, q-1); quickSort(a, q+1, e); } } public static int partion(int a[], int p, int e) { int x=a[e]; int j=p-1; for (int i = p; i < e; i++) { if (a[i]<x) { j++; int t=a[i]; a[i]=a[j]; a[j]=t; } } int t=a[j+1]; a[j+1]=a[e]; a[e]=t; return j+1; } } // public static <T> void swap (T a, T b) { // T temp=b; // b=a; // a=temp; // }
相关文章推荐
- 快速排序quicksort-算法导论java实现
- 算法导论快速排序python实现
- 【算法导论】快速排序java实现
- 快速排序的C#实现以及,算法导论上之后一个习题的思考
- 插入排序,合并排序,堆排序,快速排序,计数排序的实现(算法导论)
- 算法导论之快速排序
- 【算法导论】快速排序
- 【算法导论】第七章之快速排序
- 【算法导论实验2】快速排序与第i小数问题
- 【快速排序】算法实现
- 几种常见排序算法之Java实现(插入排序、希尔排序、冒泡排序、快速排序、选择排序、归并排序)
- 算法导论之插入排序,选择排序,归并排序,冒泡排序,希尔排序,堆排序,快速排序的c语言实现
- 笔试算法题(55):快速排序实现之三路划分, 三元中值法和插入排序处理小子文件
- python 算法 排序实现快速排序
- 经典快速排序,linux纯C实现。注意swap方法,并且这个算法还需再敲写15篇。
- 算法导论 第七章快速排序与随机快速排序
- 【算法导论 第7章 快速排序】
- 算法导论之三:快速排序
- 堆排序__算法导论实现
- 算法-快速排序-java实现