package SORT;
public class sort {
//冒泡排序
public static int[] bubble(int[] arr) {
int cnt = 0;
while(cnt < arr.length - 2) {
for(int i = 0;i < arr.length - cnt - 1; i++){
if(arr[i] > arr[i+1]) {
arr = swap(arr, i, i+1);
}
}
cnt++;
}
return arr;
}
//选择排序
public static int[] select(int[] arr) {
int last = arr.length - 1;
while(last > 0) {
int max = 1;
for(int i = 0; i <= last; i++) {
if(arr[i] > arr[max]) {
max = i;
}
}
arr = swap(arr, max, last);
last--;
}
return arr;
}
//插入
public static int[] insert(int[] arr) {
int curr = 1;
while(curr < arr.length ) {
for(int i = 0;i < curr; i++) {
if(arr[i] > arr[curr]) {
arr = redir(arr, i, curr);
}
}
curr++;
}
return arr;
}
//插入往后移动
public static int[] redir(int[] arr, int start , int curr) {
int tmp = arr[curr];
for(int i = curr; i > start; i--) {
arr[i] = arr[i-1];
}
arr[start] = tmp;
return arr;
}
//普通交换
public static int[] swap(int[] arr, int l, int r) {
int tmp;
tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
return arr;
}
public static void show(String str, int[] arr) {
if(null == arr) {
System.out.println("数组为空");
}
System.out.println(str + "数组开始打印");
for(int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {9,5,8,6,7,3,2,4,1,10};
show("bubble ", bubble(arr));
show("select ", select(arr));
show("insert", insert(arr));
}
}
public class sort {
//冒泡排序
public static int[] bubble(int[] arr) {
int cnt = 0;
while(cnt < arr.length - 2) {
for(int i = 0;i < arr.length - cnt - 1; i++){
if(arr[i] > arr[i+1]) {
arr = swap(arr, i, i+1);
}
}
cnt++;
}
return arr;
}
//选择排序
public static int[] select(int[] arr) {
int last = arr.length - 1;
while(last > 0) {
int max = 1;
for(int i = 0; i <= last; i++) {
if(arr[i] > arr[max]) {
max = i;
}
}
arr = swap(arr, max, last);
last--;
}
return arr;
}
//插入
public static int[] insert(int[] arr) {
int curr = 1;
while(curr < arr.length ) {
for(int i = 0;i < curr; i++) {
if(arr[i] > arr[curr]) {
arr = redir(arr, i, curr);
}
}
curr++;
}
return arr;
}
//插入往后移动
public static int[] redir(int[] arr, int start , int curr) {
int tmp = arr[curr];
for(int i = curr; i > start; i--) {
arr[i] = arr[i-1];
}
arr[start] = tmp;
return arr;
}
//普通交换
public static int[] swap(int[] arr, int l, int r) {
int tmp;
tmp = arr[l];
arr[l] = arr[r];
arr[r] = tmp;
return arr;
}
public static void show(String str, int[] arr) {
if(null == arr) {
System.out.println("数组为空");
}
System.out.println(str + "数组开始打印");
for(int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = {9,5,8,6,7,3,2,4,1,10};
show("bubble ", bubble(arr));
show("select ", select(arr));
show("insert", insert(arr));
}
}