作者:xuncijins | 来源:互联网 | 2023-12-14 11:16
要求:现有一组有序的字符序列a,b,c,e,f,p,u,z,要往此字符序列中插入一个新字符,要求插入新字符后任保持有序。
运行结果:
原字符序列:a b c e f p u z
待插入的字符:m
插入字符的下标:5
插入后的字符序列:a b c e f m p u z
我下午写的代码:
import java.util.*;
public class p153 {
public static void main(String[] args) {
char letter[]=new char[9];
letter[0]='a';
letter[1]='b';
letter[2]='c';
letter[3]='e';
letter[4]='f';
letter[5]='p';
letter[6]='u';
letter[7]='z';
System.out.print("原字符序列:");
Arrays.sort(letter);
for(int i=0;i<8;i++){
System.out.print(letter[i]+" ");
}
System.out.println("");
Scanner input=new Scanner(System.in);
System.out.print("待输入的字符是:");
char str=input.next().charAt(0);
for(int i=0;i
if(letter[i]>str){
System.out.println("插入字符的下标是:"+i);
break;
}
}
letter[index]=str;
for(int i=letter.length-1;str letter[i]=letter[i-1];
}
System.out.print("插入后的字符序列是:");
for(int k=0;k System.out.print(letter[k]);
}
}
}
6 个解决方案
import java.util.*;
public class p153 {
public static void main(String[] args) {
char letter[] = new char[9];
letter[0] = 'a';
letter[1] = 'b';
letter[2] = 'c';
letter[3] = 'e';
letter[4] = 'f';
letter[5] = 'p';
letter[6] = 'u';
letter[7] = 'z';
System.out.print("原字符序列:");
Arrays.sort(letter);
for (int i = 0; i < letter.length; i++) {
System.out.print(letter[i] + " ");
}
System.out.println("");
Scanner input = new Scanner(System.in);
System.out.print("待输入的字符是:");
char str = input.next().charAt(0);
int index = 0;
for (int i = 0; i < letter.length; i++) {
if (letter[i] > str) {
System.out.println("插入字符的下标是:" + i);
index = i;
break;
}
}
char[] clone = new char[letter.length+1];
for(int j=0;j<=letter.length;j++){
if(j clone[j] = letter[j];
}else if(j==index){
clone[j]=str;
}else{
clone[j] = letter[j-1];
}
}
/*letter[index] = str;
for (int i = letter.length - 1; str < letter[i]; i--) {
System.out.println("letter[i]="+letter[i]+";letter[i-1]:"+letter[i-1]);
letter[i] = letter[i - 1];
}*/
System.out.print("插入后的字符序列是:");
for (int k = 0; k < clone.length; k++) {
System.out.print(clone[k]+ " ");
}
}
}
package package1;
import java.util.Arrays;
public class TestDemo {
public static void main(String[] args) {
char[] oldArr = { 'a', 'b', 'c', 'e', 'f', 'p', 'u', 'z' };
char key = 'm';
char[] newArr = new char[oldArr.length + 1];
int pos = 0;
for (int i = 0; i < oldArr.length; i++) { //这个for循环是为了找'm'比谁小
if (key < oldArr[i]) {
pos = i;
break;
}
}
for (int j = 0; j < pos; j++) {
newArr[j] = oldArr[j];
}
newArr[pos] = key;
for(int j=pos+1;j newArr[j] = oldArr[j-1];
}
System.out.println(Arrays.toString(oldArr));
System.out.println(Arrays.toString(newArr));
}
}