1.一组乱序的字符序列m、b、p、f、a、u、z,请用冒泡排序算法,使之按字母表顺序排列
public class Work1 {
public static void main(String[] args) {
char[] num1 = { 'm', 'b', 'p', 'f', 'a', 'u', 'z' };
for (int i = 0; i < num1.length; i++) {
boolean f = false;// 判断是否进行了数据移动
for (int j = 0; j < num1.length - 1 - i; j++) {
if (num1[j] > num1[j + 1]) {// 将更小的数放在后面
char temp = num1[j];
num1[j] = num1[j + 1];
num1[j + 1] = temp;
f = true;
}
}
if (!f) {
// 没有在比较了直接结束
break;
}
}
for (char i : num1) {
System.out.print(i + " ");
}
}
}
2.一组有序的字符序列a、b、c、e、f、p、u、z,向次字符序列中插入一个新的字符,要求插入之后字符序列仍保持有序
public class Work2 {
public static void main(String[] args) {
char[] num = { 'a', 'b', 'c', 'e', 'f', 'p', 'u', 'z', 0 };
char num1 = 'h';
int index = num.length - 1;
for (int i = 0; i < num.length; i++) {
if (num[i] > num1) {
index = i;// 找到插入节点下标,并停止运行
break;
}
}
for (int i = num.length - 2; i >= index; i--) {// 将插入点以后的字符向后移动
num[i + 1] = num[i];
}
num[index] = num1;// 将字符插入
for (char i : num) {
System.out.print(i + " ");
}
}
}
3.判断一个数组是否有序
public class Work3 {
public static void main(String[] ages) {
int[] num = { 4, 8, 10, 25, 26, 35, 45 };
int cunt = 0;
int cm = 0;
for (int i = 0; i < num.length - 1; i++) {
if (num[i] > num[i + 1]) {
cunt++;// 降序数组计数器
} else {
cm++;// 升序数组计数器
}
}
// 判断计数器是否达到次数,都不达到则此数组无序
if (cunt == num.length - 1) {
System.out.print("此数组是降序数组");
} else if (cm == num.length - 1) {
System.out.print("此数组是升序数组");
} else {
System.out.print("此数组不是有序数组");
}
}
}
4.插入排序
//插入排序
public class Text4 {
public static void main(String[] ages) {
int[] num = { 54, 154, 84, 24, 1, 53, 8, 158 };
int temp=0;
int j=0;
for (int i = 1; i < num.length; i++) {
temp=num[i];
for ( j = i - 1; j >= 0; j--) {
if (temp > num[j]) {
break;
}else {
num[j+1]=num[j];
}
}
num[j+1]=temp;
}
for(int i:num) {
System.out.print(i+" ");
}
}
}