package com.sw.demo.test;
public class Test {
public static void main(String[] args) {
int[] arr = {1,7,3,2,6,5,4,8,9};
System.out.println("--------------- 排序前 ---------------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
//insertSort(arr);
//selectSort(arr);
bubbleSort(arr);
System.out.println("--------------- 排序后 ---------------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}
/**
* 冒泡排序
* @param arr
* @return
*/
public static int[] bubbleSort(int[] arr){
int tmp;
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]){
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
return arr;
}
/**
* 选择排序
* @param arr
* @return
*/
public static int [] selectSort(int[] arr){
int tmp;
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return arr;
}
/**
* 插入排序法
* @param arr
* @return
*/
public static int[] insertSort(int [] arr){
int tmp ;
for (int i = 1; i < arr.length; i++) {
for (int j = i; j >0; j--) {
if(arr[j] < arr[j-1]){
tmp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = tmp;
}else{
break;
}
}
}
return arr;
}
}