冒泡、直接插入、简单选择排序代码
public class NowSelectSort {
public static void sort(int[] arr){
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
int flag = i;
for(int j =i+1;j<arr.length;j++){
if (arr[j]<temp){
temp = arr[j];
flag = j;
}
}
int temp2 = arr[i];
arr[i] = temp;
arr[flag] = temp2;
}
}
public static void main(String[] args) {
int arr[]=new int[]{15,29,53,8,4,9,15,86};
sort(arr);
for (int t:
arr) {
System.out.print(t+" ");
}
}
}
public class NowInsertSort {
public static void sort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];
if (arr[i] < arr[i-1]) {
int j = i - 1;
while (j>=0 && arr[j]>temp){
arr[j+1]=arr[j];
j--;
}
arr[j+1] = temp;
}
}
}
public static void printArr(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
System.out.println();
}
public static void main(String[] args) {
int arr[]=new int[]{15,29,53,8,4,9,15,86};
printArr(arr);
sort(arr);
printArr(arr);
}
}
public class NowSelectSort {
public static void sort(int[] arr){
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
int flag = i;
for(int j =i+1;j<arr.length;j++){
if (arr[j]<temp){
temp = arr[j];
flag = j;
}
}
int temp2 = arr[i];
arr[i] = temp;
arr[flag] = temp2;
}
}
public static void main(String[] args) {
int arr[]=new int[]{15,29,53,8,4,9,15,86};
sort(arr);
for (int t:
arr) {
System.out.print(t+" ");
}
}
}