1.冒泡排序
package sort;
import java.util.ArrayList;
public class Bubble {
public final static int SIZE = 20;
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i = 0;i<SIZE;i++) {
list.add(i);
}
System.out.println("Before sort:");
list.forEach(obj->System.out.print(obj + " "));
System.out.println();
int temp;
for(int i = 0;i<list.size()-1;i++) {
for(int j=1;j<list.size()-i;j++) {
if(list.get(j)>list.get(j-1)) {
temp = list.get(j);
list.set(j, list.get(j-1));
list.set(j-1, temp);
}
}
}
System.out.println("Bubble sort:");
list.forEach(obj->System.out.print(obj + " "));
System.out.println();
}
}
2.选择排序
package sort;
import java.util.ArrayList;
public class Choose {
public final static int SIZE = 20;
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < SIZE; i++) {
list.add(i);
}
System.out.println("Before sort:");
list.forEach(obj -> System.out.print(obj + " "));
System.out.println();
int len = list.size();
int max;
int max_index;
int temp;
for(int i=0;i<len-1;i++) {
max = list.get(i);
max_index = i;
for(int j=i+1;j<len;j++) {
if(max<list.get(j)) {
max= list.get(j);
max_index = j;
}else {}
}
temp = list.get(i);
list.set(i, max);
list.set(max_index, temp);
}
System.out.println("Choose sort:");
list.forEach(obj -> System.out.print(obj + " "));
System.out.println();
}
}
3.插入排序
package sort;
import java.util.ArrayList;
public class Insertion {
public final static int SIZE = 20;
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < SIZE; i++) {
list.add(i);
}
System.out.println("Before sort:");
list.forEach(obj -> System.out.print(obj + " "));
System.out.println();
int len = list.size();
int cur_index;
int temp;
for(int i=1;i<len;i++) {
cur_index = i-1;
temp = list.get(i);
while(cur_index>=0 && temp>list.get(cur_index)) {
list.set(cur_index+1,list.get(cur_index));
cur_index--;
}
list.set(cur_index+1, temp);
}
System.out.println("Insertion sort:");
list.forEach(obj -> System.out.print(obj + " "));
System.out.println();
}
}
4.希尔排序
package sort;
import java.util.ArrayList;
public class Shell {
public final static int SIZE = 20;
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < SIZE; i++) {
list.add(i);
}
System.out.println("Before sort:");
list.forEach(obj -> System.out.print(obj + " "));
System.out.println();
int list_len = list.size();
int step_len = list_len/2;
int current_index;
int temp;
while(step_len>0) {
for(int i=step_len;i<list_len;i++) {
current_index = i-step_len;
temp = list.get(i);
while(current_index>=0 && temp>list.get(current_index)) {
list.set(current_index+step_len, list.get(current_index));
current_index-=step_len;
}
list.set(current_index+step_len, temp);
}
step_len/=2;
}
System.out.println("Shell sort:");
list.forEach(obj -> System.out.print(obj + " "));
System.out.println();
}
}