排序演算法-Java

HowieLee59發表於2018-08-21

從頭開始練習一遍演算法,為以後打好基礎,本次為對排序演算法的程式碼實現與部分效能分析

注:

(1)穩定:如果a原本在b前面,而a=b,排序之後a仍然在b的前面。
(2)不穩定:如果a原本在b的前面,而a=b,排序之後 a 可能會出現在 b 的後面。

 

1.氣泡排序:

package pat;

import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static void BubbleSort(int[] arr) {
		if(arr == null || arr.length < 2) {
			return ;
		}
		for(int end = arr.length - 1; end > 0; end--) {
			for(int i = 0 ; i < end;i++) {
				if(arr[i] > arr[i + 1]) {
					swap(arr,i,i+1);
				}
			}
		}
	}
	public static void swap(int[] arr,int i,int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int[] array = new int[a];
		for(int i = 0; i < a; i++) {
			array[i] = sc.nextInt();
		}
		BubbleSort(array);
		for(int i = 0 ; i < array.length - 1; i++){
			System.out.printf("%d ", array[i]);
		}
		System.out.printf("%d", array[array.length - 1]);
		sc.close();
	}
}

空間複雜度:為O(1)

時間複雜度:使用了兩重for迴圈,忽略掉低階項,去掉整數,則為O(N2),對數的操作僅僅涉及取址與交換,時間複雜度為O(1)

演算法穩定性:穩定

2.選擇排序

package pat;

import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static void SelectSort(int[] arr) {
		if(arr == null || arr.length < 2) {
			return ;
		}
		for(int i = 0 ;i < arr.length - 1; i++) {
			int min = i;
			for(int j = i + 1 ; j < arr.length;j++) {
				min = arr[j] < arr[min]?j:min;
			}
			swap(arr,i,min);
		}
	}
	public static void swap(int[] arr,int i,int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int[] array = new int[a];
		for(int i = 0; i < a; i++) {
			array[i] = sc.nextInt();
		}
		SelectSort(array);
		for(int i = 0 ; i < array.length - 1; i++){
			System.out.printf("%d ", array[i]);
		}
		System.out.printf("%d", array[array.length - 1]);
		sc.close();
	}
}

空間複雜度:O(1)

時間複雜度:最好的情況為當排序的序列有序的時候,移動記錄為0;最差的情況為當待排序序列逆序的時候,移動為3(n-1),綜上所述,時間複雜度為O(N2)

穩定性:不穩定

3.插入排序

package pat;

import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static void InsertSort(int[] arr) {
		if(arr == null || arr.length < 2) {
			return ;
		}
		for(int i = 0 ;i < arr.length; i++) {
			for(int j = i -1 ; j >= 0 && arr[j] > arr[j + 1];j--)
			swap(arr,j,j+1);
		}
	}
	public static void swap(int[] arr,int i,int j) {
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int[] array = new int[a];
		for(int i = 0; i < a; i++) {
			array[i] = sc.nextInt();
		}
		InsertSort(array);
		for(int i = 0 ; i < array.length - 1; i++){
			System.out.printf("%d ", array[i]);
		}
		System.out.printf("%d", array[array.length - 1]);
		sc.close();
	}
}

時間複雜度:穩定的時候為O(N),不穩定的時候為O(N2),跟資料狀況是有關係的 

按照最差的來規定時間複雜度。

空間複雜度:僅使用了一個O(1)

穩定性:是一種穩定的排序演算法

附:帶有對數器的插入排序

package basic_class_01;

import java.util.Arrays;

public class Code_01_InsertionSort {

	public static void insertionSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		for (int i = 1; i < arr.length; i++) {
			for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
				swap(arr, j, j + 1);
			}
		}
	}

	public static void swap(int[] arr, int i, int j) {
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}

	// for test
	public static void comparator(int[] arr) {
		Arrays.sort(arr);
	}

	// for test
	public static int[] generateRandomArray(int maxSize, int maxValue) {
		int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
		}
		return arr;
	}

	// for test
	public static int[] copyArray(int[] arr) {
		if (arr == null) {
			return null;
		}
		int[] res = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			res[i] = arr[i];
		}
		return res;
	}

	// for test
	public static boolean isEqual(int[] arr1, int[] arr2) {
		if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
			return false;
		}
		if (arr1 == null && arr2 == null) {
			return true;
		}
		if (arr1.length != arr2.length) {
			return false;
		}
		for (int i = 0; i < arr1.length; i++) {
			if (arr1[i] != arr2[i]) {
				return false;
			}
		}
		return true;
	}

	// for test
	public static void printArray(int[] arr) {
		if (arr == null) {
			return;
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}

	// for test
	public static void main(String[] args) {
		int testTime = 500000;
		int maxSize = 100;
		int maxValue = 100;
		boolean succeed = true;
		for (int i = 0; i < testTime; i++) {
			int[] arr1 = generateRandomArray(maxSize, maxValue);
			int[] arr2 = copyArray(arr1);
			insertionSort(arr1);
			comparator(arr2);
			if (!isEqual(arr1, arr2)) {
				succeed = false;
				break;
			}
		}
		System.out.println(succeed ? "Nice!" : "Fucking fucked!");

		int[] arr = generateRandomArray(maxSize, maxValue);
		printArray(arr);
		insertionSort(arr);
		printArray(arr);
	}

}

隨機產生一組數,自動產生數並且進行驗證,成功的話就列印Nice,失敗則反,

4.歸併排序

package pat;

import java.util.Arrays;
import java.util.Scanner;

public class Main{
	public static void MergeSort(int[] arr) {
		if(arr == null || arr.length < 2) {
			return ;
		}
		sort(arr,0,arr.length - 1);
	}
	public static void sort(int[] arr,int l ,int r) {
		if(l == r) {
			return ;
		}
		int mid = l + ((r - l) >> 1);
		sort(arr, l,mid);
		sort(arr,mid + 1, r);
		merge(arr,l,mid,r);
	}
	public static void merge(int[] arr,int l,int m,int r) {
		int[] help = new int[r - l + 1];
		int i = 0;
		int p1 = l;
		int p2 = m + 1;
		while(p1 <= m && p2 <= r) {
			help[i++] = arr[p1] < arr[p2] ? arr[p1++]:arr[p2++];
		}
		while(p1 <= m) {
			help[i++] = arr[p1++];
		}
		while(p2 <= r) {
			help[i++] = arr[p2++];
		}
		for(i = 0 ; i < help.length;i++) {
			arr[l + i] = help[i];
		}
	}
/*	public static void swap(int[] arr,int i,int j) {
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}*/
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int[] array = new int[a];
		for(int i = 0; i < a; i++) {
			array[i] = sc.nextInt();
		}
		MergeSort(array);
		for(int i = 0 ; i < array.length - 1; i++){
			System.out.printf("%d ", array[i]);
		}
		System.out.printf("%d", array[array.length - 1]);
		sc.close();
	}
}

時間複雜度:二路歸併排序的時間複雜度等於歸併趟數與每一趟時間複雜度的乘積。歸併的趟數為【log2n】。每一路歸併的時間複雜度為O(N),因此二路歸併排序的時間複雜度為O(nlog2n)

空間複雜度:二路歸併排序需要一個與待排序記錄序列等長的輔助陣列來存放排序過程的中間結果,所以空間複雜度為O(n)

演算法穩定度:為一種穩定的排序演算法

5.快速排序

package pat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	public static void QuickSort(int[] arr, int left, int right) {
		if (left >= right) {
			return;
		}
		int l = left, r = right, x = arr[left];
		while (l < r) {
			while (l < r && arr[r] >= x) {
				r--;
			}
			arr[l] = arr[r];
			while (l < r && arr[l] <= x) {
				l++;
			}
			arr[r] = arr[l];
		}
		arr[l] = x;
		QuickSort(arr, left, r - 1);
		QuickSort(arr, r + 1, right);
	}

	/*
	 * public static void swap(int[] arr,int i,int j) { if(i != j) { arr[i] = arr[i]
	 * ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } }
	 */
	public static void main(String[] args) throws IOException{
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		while (in.nextToken() != StreamTokenizer.TT_EOF) {
			int a = (int) in.nval;
			in.nextToken();
			int[] array = new int[a];
			for (int i = 0; i < a -1; i++) {
				array[i] = (int) in.nval;
				in.nextToken();
			}
			array[a -1] = (int) in.nval;
			StringBuilder sc = new StringBuilder();
			QuickSort(array, 0, a - 1);
			for (int i = 0; i < a - 1; i++) {
				sc.append(array[i] + " ");
			}
			sc.append(array[a - 1]);
			out.print(sc);
			out.println();
			out.flush();/*重新整理輸出緩衝區*/
		}
		
	}
}

時間複雜度:最好的情況下為O(nlog2n),最壞的情況下相當於氣泡排序,時間複雜度為O(n2)

空間複雜度:最好的情況下為O(log2n),最壞的情況下為O(n),空間花在斷點中,pivot點

穩定性:是一種不穩定的排序演算法

附:

package basic_class_01;

import java.util.Arrays;

public class Code_04_QuickSort {

	public static void quickSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		quickSort(arr, 0, arr.length - 1);
	}

	public static void quickSort(int[] arr, int l, int r) {
		if (l < r) {
			swap(arr, l + (int) (Math.random() * (r - l + 1)), r);
			int[] p = partition(arr, l, r);
			quickSort(arr, l, p[0] - 1);
			quickSort(arr, p[1] + 1, r);
		}
	}

	public static int[] partition(int[] arr, int l, int r) {
		int less = l - 1;
		int more = r;
		while (l < more) {
			if (arr[l] < arr[r]) {
				swap(arr, ++less, l++);
			} else if (arr[l] > arr[r]) {
				swap(arr, --more, l);
			} else {
				l++;
			}
		}
		swap(arr, more, r);
		return new int[] { less + 1, more };
	}

	public static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}

	// for test
	public static void comparator(int[] arr) {
		Arrays.sort(arr);
	}

	// for test
	public static int[] generateRandomArray(int maxSize, int maxValue) {
		int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
		}
		return arr;
	}

	// for test
	public static int[] copyArray(int[] arr) {
		if (arr == null) {
			return null;
		}
		int[] res = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			res[i] = arr[i];
		}
		return res;
	}

	// for test
	public static boolean isEqual(int[] arr1, int[] arr2) {
		if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
			return false;
		}
		if (arr1 == null && arr2 == null) {
			return true;
		}
		if (arr1.length != arr2.length) {
			return false;
		}
		for (int i = 0; i < arr1.length; i++) {
			if (arr1[i] != arr2[i]) {
				return false;
			}
		}
		return true;
	}

	// for test
	public static void printArray(int[] arr) {
		if (arr == null) {
			return;
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}

	// for test
	public static void main(String[] args) {
		int testTime = 500000;
		int maxSize = 100;
		int maxValue = 100;
		boolean succeed = true;
		for (int i = 0; i < testTime; i++) {
			int[] arr1 = generateRandomArray(maxSize, maxValue);
			int[] arr2 = copyArray(arr1);
			quickSort(arr1);
			comparator(arr2);
			if (!isEqual(arr1, arr2)) {
				succeed = false;
				printArray(arr1);
				printArray(arr2);
				break;
			}
		}
		System.out.println(succeed ? "Nice!" : "Fucking fucked!");

		int[] arr = generateRandomArray(maxSize, maxValue);
		printArray(arr);
		quickSort(arr);
		printArray(arr);

	}

}

6.堆排序

package basic_class_01;

import java.util.Arrays;

public class Code_03_HeapSort {

	public static void heapSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		for (int i = 0; i < arr.length; i++) {
			heapInsert(arr, i);
		}
		int size = arr.length;
		swap(arr, 0, --size);
		while (size > 0) {
			heapify(arr, 0, size);
			swap(arr, 0, --size);
		}
	}

	public static void heapInsert(int[] arr, int index) {
		while (arr[index] > arr[(index - 1) / 2]) {
			swap(arr, index, (index - 1) / 2);
			index = (index - 1) / 2;
		}
	}

	public static void heapify(int[] arr, int index, int size) {
		int left = index * 2 + 1;
		while (left < size) {
			int largest = left + 1 < size && arr[left + 1] > arr[left] ? left + 1 : left;
			largest = arr[largest] > arr[index] ? largest : index;
			if (largest == index) {
				break;
			}
			swap(arr, largest, index);
			index = largest;
			left = index * 2 + 1;
		}
	}

	public static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}

	// for test
	public static void comparator(int[] arr) {
		Arrays.sort(arr);
	}

	// for test
	public static int[] generateRandomArray(int maxSize, int maxValue) {
		int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
		}
		return arr;
	}

	// for test
	public static int[] copyArray(int[] arr) {
		if (arr == null) {
			return null;
		}
		int[] res = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			res[i] = arr[i];
		}
		return res;
	}

	// for test
	public static boolean isEqual(int[] arr1, int[] arr2) {
		if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
			return false;
		}
		if (arr1 == null && arr2 == null) {
			return true;
		}
		if (arr1.length != arr2.length) {
			return false;
		}
		for (int i = 0; i < arr1.length; i++) {
			if (arr1[i] != arr2[i]) {
				return false;
			}
		}
		return true;
	}

	// for test
	public static void printArray(int[] arr) {
		if (arr == null) {
			return;
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}

	// for test
	public static void main(String[] args) {
		int testTime = 500000;
		int maxSize = 100;
		int maxValue = 100;
		boolean succeed = true;
		for (int i = 0; i < testTime; i++) {
			int[] arr1 = generateRandomArray(maxSize, maxValue);
			int[] arr2 = copyArray(arr1);
			heapSort(arr1);
			comparator(arr2);
			if (!isEqual(arr1, arr2)) {
				succeed = false;
				break;
			}
		}
		System.out.println(succeed ? "Nice!" : "Fucking fucked!");

		int[] arr = generateRandomArray(maxSize, maxValue);
		printArray(arr);
		heapSort(arr);
		printArray(arr);
	}

}

空間複雜度:堆排需要一個記錄的輔助儲存空間,空間複雜度為O(1)

時間複雜度:在最壞的情況下,堆排序的時間複雜度為O(nlog2n)

穩定性:堆排序演算法是一種不穩定的排序演算法

7.桶排序

package basic_class_01;

import java.util.Arrays;

public class Code_06_BucketSort {

	// only for 0~200 value
	public static void bucketSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		int max = Integer.MIN_VALUE;
		for (int i = 0; i < arr.length; i++) {
			max = Math.max(max, arr[i]);
		}
		int[] bucket = new int[max + 1];
		for (int i = 0; i < arr.length; i++) {
			bucket[arr[i]]++;
		}
		int i = 0;
		for (int j = 0; j < bucket.length; j++) {
			while (bucket[j]-- > 0) {
				arr[i++] = j;
			}
		}
	}

	// for test
	public static void comparator(int[] arr) {
		Arrays.sort(arr);
	}

	// for test
	public static int[] generateRandomArray(int maxSize, int maxValue) {
		int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = (int) ((maxValue + 1) * Math.random());
		}
		return arr;
	}

	// for test
	public static int[] copyArray(int[] arr) {
		if (arr == null) {
			return null;
		}
		int[] res = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			res[i] = arr[i];
		}
		return res;
	}

	// for test
	public static boolean isEqual(int[] arr1, int[] arr2) {
		if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
			return false;
		}
		if (arr1 == null && arr2 == null) {
			return true;
		}
		if (arr1.length != arr2.length) {
			return false;
		}
		for (int i = 0; i < arr1.length; i++) {
			if (arr1[i] != arr2[i]) {
				return false;
			}
		}
		return true;
	}

	// for test
	public static void printArray(int[] arr) {
		if (arr == null) {
			return;
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}

	// for test
	public static void main(String[] args) {
		int testTime = 500000;
		int maxSize = 100;
		int maxValue = 150;
		boolean succeed = true;
		for (int i = 0; i < testTime; i++) {
			int[] arr1 = generateRandomArray(maxSize, maxValue);
			int[] arr2 = copyArray(arr1);
			bucketSort(arr1);
			comparator(arr2);
			if (!isEqual(arr1, arr2)) {
				succeed = false;
				printArray(arr1);
				printArray(arr2);
				break;
			}
		}
		System.out.println(succeed ? "Nice!" : "Fucking fucked!");

		int[] arr = generateRandomArray(maxSize, maxValue);
		printArray(arr);
		bucketSort(arr);
		printArray(arr);

	}

}

時間複雜度:O(N)

空間複雜度:O(N+M)

穩定性:穩定

8.比較器

package basic_class_01;

import java.util.Arrays;
import java.util.Comparator;

public class Code_09_Comparator {

	public static class Student {
		public String name;
		public int id;
		public int age;

		public Student(String name, int id, int age) {
			this.name = name;
			this.id = id;
			this.age = age;
		}
	}

	public static class IdAscendingComparator implements Comparator<Student> {

		@Override
		public int compare(Student o1, Student o2) {
			return o1.id - o2.id;
		}

	}

	public static class IdDescendingComparator implements Comparator<Student> {

		@Override
		public int compare(Student o1, Student o2) {
			return o2.id - o1.id;
		}

	}

	public static class AgeAscendingComparator implements Comparator<Student> {

		@Override
		public int compare(Student o1, Student o2) {
			return o1.age - o2.age;
		}

	}

	public static class AgeDescendingComparator implements Comparator<Student> {

		@Override
		public int compare(Student o1, Student o2) {
			return o2.age - o1.age;
		}

	}

	public static void printStudents(Student[] students) {
		for (Student student : students) {
			System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age);
		}
		System.out.println("===========================");
	}

	public static void main(String[] args) {
		Student student1 = new Student("A", 1, 23);
		Student student2 = new Student("B", 2, 21);
		Student student3 = new Student("C", 3, 22);

		Student[] students = new Student[] { student3, student2, student1 };
		printStudents(students);

		Arrays.sort(students, new IdAscendingComparator());
		printStudents(students);

		Arrays.sort(students, new IdDescendingComparator());
		printStudents(students);

		Arrays.sort(students, new AgeAscendingComparator());
		printStudents(students);

		Arrays.sort(students, new AgeDescendingComparator());
		printStudents(students);

	}

}

未完待續

相關文章