数组排序方式
冒泡排序
import java.util.Random;
public class Bubbling {
public static void main(String[] args){
Random rand = new Random(1024);
int[] arr = new int[10];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100);
}
for (int i=0; i<arr.length-1; i++) {
for (int j=0; j<arr.length-1-i; j++) {
if(arr[j]>arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
}
选择排序
import java.util.Random;
public class Selection {
public static void main(String[] args){
Random rand = new Random(1024);
int[] arr = new int[10];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100);
}
for (int i=0; i<arr.length-1; i++) {
int last = arr.length-1-i;
int max = 0;
for (int j=1; j<arr.length-i; j++) {
if (arr[j] > arr[max]) {
max = j;
}
}
if (max != last) {
int temp = arr[last];
arr[last] = arr[max];
arr[max] = temp;
}
}
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
}
插入排序
import java.util.Random;
public class Insertion {
public static void main(String[] args){
Random rand = new Random(1024);
int[] arr = new int[10];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100);
}
for (int i=0; i<arr.length-1; i++) {
int start = arr[i+1];
for (int j=i; j>=0 && start < arr[j]; j--) {
arr[j+1] = arr[j];
arr[j] = start;
}
}
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
}
希尔排序
import java.util.Random;
public class Hill {
public static void main(String[] args){
Random rand = new Random(2048);
int[] arr = new int[10];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100);
}
for (int jump=arr.length/2; jump>=1; jump/=2) {
for (int i=jump; i<arr.length; i++) {
int start = arr[i];
for (int j=i-jump; j>=0 && start < arr[j]; j-=jump) {
arr[j+jump] = arr[j];
arr[j] = start;
}
}
}
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
}
快速排序
import java.util.Random;
public class Quick {
public void quickSort(int[] arr,int low,int high){
if (low >= high) {
return;
}
int left,right,base;
left = low;
right = high;
base = arr[low];
while (left != right) {
while (left < right && arr[right] >= base) {
right--;
}
while (left < right && arr[left] <= base ) {
left++;
}
if (left < right) {
int temp = arr[right];
arr[right] = arr[left];
arr[left] = temp;
}
}
arr[low] = arr[left];
arr[left] = base;
left--;right++;
quickSort(arr,low,left);
quickSort(arr,right,high);
}
public void show(int[] arr){
for (int i=0; i<arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
public static void main(String[] args){
Random rand = new Random();
int[] arr = new int[20];
for (int i=0; i<arr.length; i++) {
arr[i] = rand.nextInt(100);
}
Quick q = new Quick();
q.quickSort(arr,0,arr.length-1);
q.show(arr);
}
}