import java.util.Scanner;
/*直接插入排序:依次为每个元素找在以排好序列的位置
*稳定排序(相同元素在排序过程保持之间前后位置不变。)
*期望复杂度:O(n2)
*/
public class InsertSort {
public static void main(String[] args) {
//控制台读入字符串,以逗号分隔 (1,2,3,4)
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
//分隔成单个字符
String[] strs = str.split(",");
//进入循环,确定每个数字位置
for (int i = 1; i<strs.length; i++) {
int j = i-1;
String temp = strs[i];
//依次与之前的数字比较,如果小于前面的数字,则前面数字后移,直到确定位置或者j==0
while (j>=0 && Integer.parseInt(strs[j]) > Integer.parseInt(temp)) {
strs[j+1] = strs[j];
j--;
}
strs[j+1] = temp;
}
//输出排序结果
for (String string : strs) {
System.out.println(string);
}
}
}
import java.util.Scanner;
/*希尔排序:把记录按下标的一定分量分组,然后两两比较,交换先后位置
*不稳定排序(即相同的数字在排序后会改变位置 排序前a1....a3|排序后a3...a1 a1=a3)
*时间复杂度:O(nlog2n)
*/
public class ShellSort {
public static void main(String[] args) {
//读入字符串并分隔成字符数组(1,2,3,4)
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String[] strs = str.split(",");
double d = strs.length;
while (true) {
//按d/2取地板进行分组
d = Math.ceil(d/2);
int d1 = (int)d;
//按组数进入循环
for (int i = 0; i < d1; i++) {
//每组从最前两个开始依次比较,交换位置
for ( int x = i+d1; x < strs.length; x += d1) {
int j = x - d1;
if (Integer.parseInt(strs[j]) > Integer.parseInt(strs[x])) {
String temp = strs[j];
strs[j] = strs[x];
strs[x] = temp;
}
}
}
if (d1 == 1) {
break;
}
}
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
}
}
/*冒泡排序
*稳定排序
*期望复杂度:O(n2)
* */
public class BubbleSort {
public static void main(String[] args) {
int a[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51};
int temp=0;
//用来判断是否发生位置交换,初始为true
boolean judge = true;
while(judge) {
judge = false;
for (int i=0; i<a.length-1; i++){
if (a[i] > a[i+1]) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
//发生位置交换后为true,继续循环比较
judge = true;
}
}
}
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
}
}