背模板
C++ 代码
#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int q[N];
void swap_q(int q[], int x, int y)
{
if(x == y) return;
int z = q[x + y >> 1], i = x - 1, j = y + 1;
while(i < j)
{
do i++; while(q[i] < z);
do j--; while(q[j] > z);
if(i < j) swap(q[i] ,q[j]);
}
swap_q(q, x, j);
swap_q(q, j + 1, y);
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> q[i];
swap_q(q, 0, n - 1);
for(int i = 0; i < n; i++)
cout << q[i] << " ";
return 0;
}
Java 代码
import java.util.Scanner;
public class Main
{
static int N = 1000010;
static int q[] = new int[N];
public static void main(String[] args)
{
Scanner get = new Scanner(System.in);
int n = get.nextInt();
for(int i = 0; i < n; i++)
q[i] = get.nextInt();
swap_q(q, 0, n - 1);
for(int i = 0; i < n; i++)
System.out.print(q[i] + " ");
}
public static void swap_q(int q[], int x, int y)
{
if(x == y) return;
int z = q[x + y >> 1], i = x - 1, j = y + 1;
while(i < j)
{
do i++; while(q[i] < z);
do j--; while(q[j] > z);
if(i < j)
{
q[i] = q[i] + q[j];
q[j] = q[i] - q[j];
q[i] = q[i] - q[j];
}
}
swap_q(q, x, j);
swap_q(q, j + 1, y);
}
}