整理文檔,搜刮出一個(gè)java實(shí)現(xiàn)向有序數(shù)組中插入一個(gè)元素,稍微整理精簡(jiǎn)一下做下分享

package cn.jbit.array;
import java.util.*;
public class Insert {
public static void main(String[] args) {
//字符排序
char[] chars = new char[9];
chars[0] = 'a';
chars[1] = 'c';
chars[2] = 'u';
chars[3] = 'b';
chars[4] = 'e';
chars[5] = 'p';
chars[6] = 'f';
chars[7] = 'z';
System.out.print("原字符序列:");
for(int i = 0; i < chars.length; i++){
System.out.print(chars[i] + " ");
}
Arrays.sort(chars); //對(duì)數(shù)組進(jìn)行升序排序
System.out.print("\n升序排序后:");
for(int i = 0; i < chars.length; i++){
System.out.print(chars[i] + " ");
}
//實(shí)現(xiàn)插入字符
int index = chars.length; //保存新增成績(jī)插入位置
char ch='m';
System.out.println("\n待插入的字符是: "+ch);
//找到新元素的插入位置
for(int i = 0; i < chars.length; i++){
if(ch < chars[i]){
index = i;
break;
}
}
//元素后移
for(int j = chars.length-1; j > index; j--){
chars[j] = chars[j-1]; //index下標(biāo)開始的元素后移一個(gè)位置
}
chars[index] = ch;//插入數(shù)據(jù)
System.out.println("插入字符的下標(biāo)是:"+index);
System.out.print("插入后的字符序列是: ");
for (int k = 0; k < chars.length; k++) { // 循環(huán)輸出目前數(shù)組中的數(shù)據(jù)
System.out.print(chars[k] + " ");
}
}
}
分享標(biāo)題:java實(shí)現(xiàn)向有序數(shù)組中插入一個(gè)元素實(shí)例-創(chuàng)新互聯(lián)
網(wǎng)站路徑:http://chinadenli.net/article38/cojgsp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、網(wǎng)站改版、虛擬主機(jī)、云服務(wù)器、商城網(wǎng)站、網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容