當前位置:首頁 » 編程語言 » 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-09-19 01:58:55 瀏覽:159
我的世界國際版伺服器地址名稱 發布:2025-09-19 01:52:24 瀏覽:331
河北智慧黨建密碼是多少 發布:2025-09-19 01:51:08 瀏覽:657
winform反編譯 發布:2025-09-19 01:43:48 瀏覽:916
c語言中怎麼賦值 發布:2025-09-19 01:17:43 瀏覽:957
公網伺服器如何共享ip 發布:2025-09-19 01:03:43 瀏覽:238
存儲器已幾乎滿 發布:2025-09-19 00:36:28 瀏覽:885
安卓系統在哪裡輸入網址 發布:2025-09-19 00:35:46 瀏覽:174
armlinuxgccgcc 發布:2025-09-19 00:35:37 瀏覽:426
wincachephp 發布:2025-09-19 00:30:28 瀏覽:866