當前位置:首頁 » 編程語言 » 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介面

熱點內容
ftp建立win10 發布:2024-05-22 06:27:02 瀏覽:844
蘋果怎麼改安卓系統 發布:2024-05-22 06:21:21 瀏覽:19
飛兒精品教程解壓密碼 發布:2024-05-22 06:21:17 瀏覽:902
mysql自動備份腳本 發布:2024-05-22 05:55:16 瀏覽:931
c語言單片機埠 發布:2024-05-22 05:55:05 瀏覽:163
c目錄文件夾 發布:2024-05-22 05:36:45 瀏覽:108
編程貓微課 發布:2024-05-22 05:36:37 瀏覽:656
兒童編程的書 發布:2024-05-22 05:35:49 瀏覽:581
加密技術挑戰 發布:2024-05-22 05:09:01 瀏覽:986
懷舊服玩小號去什麼伺服器 發布:2024-05-22 04:52:22 瀏覽:559