當前位置:首頁 » 編程語言 » java排序插入

java排序插入

發布時間: 2023-03-07 09:00:44

A. java插入排序

Java程序入口是main函數,
而main函數的參數必須是String[] args;

所以你要把函數名mian改成其他如sort,並新寫一個main函數來調用他。
public static void main(String[] args){
}

B. JAVA實現插入排序

public class Test {

public static void main(String[] args) {
int[] source = { 1, 3, 2, 5, 12, 3, 123, 23, 2, 541, 1, 76, 76 };
Test test = new Test();
test.printArray(source);
test.insertSort(source);
test.printArray(source);
}

public void insertSort(int[] source) {
for (int i = 1; i < source.length; i++) {
for (int j = i; (j > 0) && (source[j] < source[j - 1]); j--) {
swap(source, j, j - 1);
}
}
printArray(source);// 輸出插入排序後的數組值
}

private void swap(int[] source, int x, int y) {
int temp = source[x];
source[x] = source[y];
source[y] = temp;
}

public void printArray(int[] source) {
for (int i : source) {
System.out.print(i + " ");
}
System.out.println();
}
}

C. JAVA一個已經排好序的數組(元素為10個),插入一個數按照原來的排序

1、數組插入新數據,首先需要擴容,java中數組需要使用數組的擴容方式:arr = Arrays.Of(arr, arr.length+1);
或者,//已有 int [] num ;
num = new int[num.length+1];重新定義數組,之後按順序遍歷插入,或者插入以後再排序也是可以的。

D. JAVA 字母排序,並插入字母後再次排序

//數組方式
String[]arr={"c","d","b","a"};
java.util.Arrays.sort(arr);
System.out.println(java.util.Arrays.toString(arr));//輸出數組

//使用TreeSet排序
TreeSet<String>ts=newTreeSet<String>();
ts.add("c");
ts.add("a");
ts.add("b");
System.out.println(ts);//輸出排序後的
//PS:因為TreeSet存在自然排序,所以不必實現Comparator還有Comparable介面

熱點內容
隨機啟動腳本 發布:2025-07-05 16:10:30 瀏覽:515
微博資料庫設計 發布:2025-07-05 15:30:55 瀏覽:19
linux485 發布:2025-07-05 14:38:28 瀏覽:299
php用的軟體 發布:2025-07-05 14:06:22 瀏覽:750
沒有許可權訪問計算機 發布:2025-07-05 13:29:11 瀏覽:425
javaweb開發教程視頻教程 發布:2025-07-05 13:24:41 瀏覽:684
康師傅控流腳本破解 發布:2025-07-05 13:17:27 瀏覽:233
java的開發流程 發布:2025-07-05 12:45:11 瀏覽:678
怎麼看內存卡配置 發布:2025-07-05 12:29:19 瀏覽:277
訪問學者英文個人簡歷 發布:2025-07-05 12:29:17 瀏覽:828