插入排序
package com.zc.manythread;
/**
* 插入排序
* @author 偶my耶
*
*/
public class InsertionSort {
public static void insertion_sort(int[] data) {//
for (int i = 1; i < data.length; i++) {
if (data[i - 1] > data[i]) {
int temp = data[i];
int j = i;
while (j > 0 && data[j - 1] > temp) {
data[j] = data[j - 1];
j--;
}
data[j] = temp;
}
}
}
public static void main(String[] args) {
int[] data = { 6, 2, 4, 1, 5, 9 };
insertion_sort(data);
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + "\t");
}
}
}
選擇排序是一類藉助“選擇” 進行排序的方法。其主要思想是:沒趟排序在當前排序序列中選出關鍵碼最小的記錄,天機到有序序列中。選擇排序比較獨特的地方是:記錄的移動次數少。
選擇排序源代碼:
package com.zc.manythread;
/**
* 選擇排序
* @author Administrator
*
*/
public class SelectSort {
/**
* 快速排序
* @param date
* @return
*/
int[] SelectSort(int[] date){
for (int i = 0; i < date.length-1; i++) {
int index=i;
for (int j = i+1; j < date.length; j++) {
if (date[j]<date[index]) {
index=j;
}
}
if (index!=i) {
int temp=date[i];
date[i]=date[index];
date[index]=temp;
}
}
return date;
}
/**************
*
* 創建數組數據
* *****************/
private static int[] createDate(int count) {
int[] data=new int[count];
for (int i = 0; i < data.length; i++) {
data[i]=(int)(Math.random()*count);
}
return data;
}
/**************主函數*****************/
public static void main(String[] args) {
final int count=10;
int[] data=createDate(count);
for (int n:data) {
System.out.print(n+"\t");
}
System.out.println();
int[] data2=new SelectSort().SelectSort(data);
for (int n:data) {
System.out.print(n+"\t");
}
}
}
博客地址: | http://www.cnblogs.com/oumyye/ |
博客版權: | 本文以學習、研究和分享爲主,歡迎轉載,轉載請務必註明出處,謝謝合作。 如果文中有不妥或者錯誤的地方請指出。如果覺得本文對你有所幫助不如【推薦】一下!如果你有更好的建議,不如留言一起討論,共同進步! |