Java(二)

來源:互聯網
上載者:User

標籤:順序   ++   exti   rgs   int()   原理   插入   預設值   aix   

二維數組是由一維數組組成的數組
選擇排序原理
將數組中每一個元素與第一個元素相比較,如果這個元素小於第一個元素,則交換這兩個元素
迴圈第一條規則,找出最小元素,放於第一個位置
經過n-1輪比較完成排序

冒泡排序原理
逐一比較數組中相鄰的兩個元素,如果後面的元素小於前面的元素就交換相互順序
經過一輪比較,一定有一個最大的排在最後的位置
每次比較剩下的元素,經過n-1輪比較完成排序

插入排序原理
將數組分為兩部分,將後部分的第一張逐一與前部分每一張比較,如果當前元素小,就移動被比較元素。找到合理位置插入

1.概念:二維數組是由一維數組組成的數組


2.文法:a.int [] [] arr=new int [2][];
定義了二維數組的長度,但是一維數組長度沒有定義,一維數組沒有申請記憶體空間null
b.int [] [] arr=new int [2][3];
定義了一維數組和二維數組的長度,一維數組分配了記憶體空間,一維數組的長度為3,一維數組的預設值為0;
c.二維數組也支援靜態初始化
String [] []arr={{0,1,5,},{6,5,2}}

數組經典排序

1.選擇排序原理
a.將數組中每個元素與第一個元素比較,如果這個元素小於第一個元素,則交換這倆個元素的位置
b.迴圈第一條規則,找出最小元素,防於第一個位置
c.經過N-1輪比較完成排序


package paixu;

/**
* 選擇排序
*/
import java.util.Scanner;

public class zy2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("請輸入輸入數位位元:");
int c = input.nextInt();
int[] a = new int[c];
for (int i = 0; i < a.length; i++) {
System.out.print("請輸入輸第" + (i + 1) + "位元字:");
a[i] = input.nextInt();
}
int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
}
}


2.冒泡排序原理
a.逐一比較數組中相鄰的兩個元素,如果後面的元素小於前面的元素就互換
b.經過一輪比較,一定有一個最大的排在最後的位置
c.每一次比較剩下的元素,經過N-1次比較可以實現排序

1 package paixu;
2
3 /**
4 * 冒泡排序
5 */
6
7 public class zy1 {
8 public static void main(String[] args) {
9 int[] sz = { 8, 6, 5, 4, 3, 1, 2 };
10 int bl = 0;
11 for (int i = 0; i < sz.length - 1; i++) {
12 for (int j = 0; j < sz.length - 1 - i; j++) {
13 if (sz[j] > sz[j + 1]) {
14 bl = sz[j];
15 sz[j] = sz[j + 1];
16 sz[j + 1] = bl;
17 }
18 }
19 }
20 for (int i = 0; i < sz.length; i++) {
21 System.out.print(sz[i] + "\t");
22 }
23 }
24
25 }

3.插入排序原理
a.將數組分為兩部分,將後部分的第一張逐一與前部分每一張比較,如果當前元素小,就移動被比較的元素
b.找到合理位置插入

1 package paixu;
2
3 /**
4 * 插入排序
5 */
6 public class zy3 {
7 public static void main(String[] args) {
8 int[] sz = { 1, 9, 5, 2, 7, 4 };
9 for (int i = 1; i < sz.length; i++) {
10 int temp = sz[i];
11 int j;
12 for (j = i - 1; j >= 0; j--) {
13 if (temp < sz[j]) {
14 sz[j + 1] = sz[j];// 元素向後移動
15 } else {
16 break;
17 }
18 }
19 sz[j + 1] = temp;// 找到合適的位值插入元素
20 }
21 for (int i = 0; i < sz.length; i++) {
22 System.out.print(sz[i] + " ");
23 }
24 }
25 }

Java(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.