當前位置:編程學習大全網 - 編程軟體 - java編程問題。用兩個for循環來把輸入的整數從小到大排序。

java編程問題。用兩個for循環來把輸入的整數從小到大排序。

這樣的代碼看的費勁

數組排序的方法有冒泡和選擇比較的好理解:

代碼如下:

package com.tx.wl.p10;

public class ArrayDemo {

public static void main(String[] args) {

int[] a = { 3, 43, 22, 4, 22, 31, 23 };

System.out.println("遍歷數組:");

showArray(a);

System.out.println("冒泡排序:");

maoPao(a);

showArray(a);

System.out.println("選擇排序:");

xuanze(a);

showArray(a);

}

private static void xuanze(int[] a) {

int[] b = a;

for (int i = 0; i < b.length; i++) {

int index = i;

for (int j = i; j < b.length; j++) {

if (a[index] > b[j]) {

index = j;

}

}

int temp = b[index];

b[index] = b[i];

b[i] = temp;

}

}

private static void maoPao(int[] a) {

int[] c = a;

for (int i = 0; i < c.length; i++) {

for (int j = 0; j < c.length - i - 1; j++) {

if (c[j] > c[j + 1]) {

int temp = c[j];

c[j] = c[j + 1];

c[j + 1] = temp;

}

}

}

}

private static void showArray(int[] a) {

for (int aa : a) {

System.out.print(aa + " ");

}

System.out.println();

}

}

理解型記憶,裏面的遍歷用的是增強for,原理就相當於

for(int i=0; i<a.length;i++){

System.ou.tprintln(a[i]);

}

  • 上一篇:dfmkhaa**jzkznjw是什麽意思
  • 下一篇:如何用excle寫python?
  • copyright 2024編程學習大全網