快速排序
c++
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e5+10;
int n,a[N];
void quicksort(int l,int r)
{
if(l>=r)return;
int mid=(l+r)/2;
int x=a[mid];
int i=l-1,j=r+1;
while(i<j){
do i++;while(a[i]<x);
do j--;while(a[j]>x);
if(i<j)swap(a[i],a[j]);
}
quicksort(l,j);
quicksort(j+1,r);
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
quicksort(1,n);
for(int i=1;i<=n;i++)
cout<<a[i]<<' ';
}
java
import java.util.*;
public class quicksort {
static Scanner sc = new Scanner(System.in);
static int n = sc.nextInt();
static int[] q = new int[n];
public static void main(String[] args) {
for (int i = 0; i < n; i++) {
q[i] = sc.nextInt();
}
QuickSort(0, n - 1);
for (int i = 0; i < n; i++) {
System.out.print(q[i] + " ");
}
}
public static void QuickSort(int l,int r){
if(l>=r)return;
int x=q[l+r>>1],i=l-1,j=r+1;
while(i<j){
do i++;while(q[i]<x);
do j--;while(q[j]>x);
if(i<j){
int t=q[i];
q[i]=q[j];
q[j]=t;
}
}
QuickSort(l,j);
QuickSort(j+1,r);
System.out.println();
}
}
文章评论