选择插入:
public static void selectionSort(int[] arr) {
for(int i = 0 ; i < arr.length ; i++) {
int minIndex = i;
for (int j = i+1 ; j < arr.length ; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j ;
}
}
swap(arr,i,minIndex);
}
}
private static void swap(int[] arr, int i,int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public class SelectionSort {
public static void selectionSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for(int i = 0; i <arr.length ; i++) {
int minIndex = i ;
for (int j = i ; j < arr.length ; j ++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i]= arr[minIndex];
arr[minIndex]=temp;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {2,5,1,6,8,3,7};
for (int num : arr)
System.out.print(num + " ");
System.out.println();
selectionSort(arr);
for (int num1 : arr)
System.out.print(num1+" ");
}
}
插入排序:
public static void insertionSort(int[] arr) {
for(int i = 0 ; i < arr.length ; i++) {
int insertVal = arr[i]; // 插入元素
int index = i; //插入位置
for(; index > 0 ; index--) {
if(insertVal < arr[index-1]) {
arr[index] = arr[index-1];
else
break;
}
}
arr[index] = insertVal; //把元素插入
}
}
冒泡排序 :
public static void bubbleSort(int[] arr) {
for (int i = arr.length - 1 ; i > 0 ; i-- ) { //最后位开始确认
boolean swapped = false ;
for (int j = 0 ; j < i ; j++) {
if (arr[j] < arr[j+1]) {
swapped = true;
swap (arr,j,j+1);
}
}
if(!swapped)
return;
}
}
private static void swap (int[] arr,int i,int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public class BubbleSort1 {
public static void bubbleSort(int[] arr) {
if(arr == null || arr.length < 2) {
return;
}
for(int i = 0; i < arr.length ; 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;
}
}
}
}
public static void main (String[] args) {
int arr[] = {2,5,1,6,8,3,7};
for (int num : arr)
System.out.print(num + " ");
System.out.println();
bubbleSort(arr);
for (int num1 : arr)
System.out.print(num1+" ");
}
}