标签:
一冒泡排序
二选择排序
三插入排序
下面我们分步讲一下这三种排序。首先来看一下冒泡排序。
package ch02; public class BubbleSort { public static void sort(long [] arr){ long temp = 0; for (int i = 0;i<arr.length-1;i++) {//i表示第几趟排序 for (int j = arr.length-1;j>i;j--) { if (arr[j] <arr[j-1]) { //交换 temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; } } } } public static void main(String[] args) { long[]arr = new long[5]; arr[0] = 34; arr[1] = 23; arr[2] = 1; arr[3] = 2; sort(arr); for (int i = 0;i<arr.length;i++) { System.out.print(arr[i]+" "); } } }
2:选择排序:代码实现
package ch02; public class SelectionSort { public static void sort(long [] arr){ int k = 0; long temp = 0; for (int i = 0;i<arr.length;i++) {//趟数 k = i; for (int j = i;j<arr.length;j++) { if (arr[j] < arr[k]) {//选择最小的交换 k = j; } }
//交换 temp = arr[i]; arr[i] = arr[k]; arr[k] = temp; } } public static void main(String[] args) { long[]arr = new long[5]; arr[0] = 34; arr[1] = 23; arr[2] = 1; arr[3] = 2; sort(arr); for (int i = 0;i<arr.length;i++) { System.out.print(arr[i]+" "); } } }
3,插入排序:代码实现(代码有问题)
package ch02; public class InsertSort { public static void sort(long [] arr){ long temp = 0; for (int i = 1;i<arr.length;i++) { temp = arr[i]; int j = i; while (j > 0 && arr[j] >= temp) { arr[j] = arr[j-1]; j--; } arr[j] = temp; } } public static void main(String[] args) { long[]arr = new long[5]; arr[0] = 34; arr[1] = 23; arr[2] = 1; arr[3] = 2; arr[4] = 0; sort(arr); for (int i = 0;i<arr.length;i++) { System.out.print(arr[i]+" "); } } }
标签:
原文地址:http://www.cnblogs.com/airycode/p/5310460.html