1.java 數組冒泡排序
排序的基本原理(升序):
- 原始數據: 2 、1 、9 、0 、5 、3 、7 、6 、8;
- 第一次排序: 1 、2 、0 、5 、3 、7 、6 、8 、9 ;
- 第二次排序: 1 、0 、2 、3 、5 、6 、7 、8 、9 ;
- 第三次排序 : 1 、 2 、3 、4 、5 、6 、7 、8 、9 ;
以上是基礎的原理過程,但是有一個問題,數據的不同可能排序的次數出現不同,但是有多少個數據,總的排序次數不會超過數組的長度。只要排序的次數達到長度*長度的次數,那么所有的數據就可以排序成功。
進行冒泡排序:
public class 數組的排序 { public static void main(String[] args) { int data[] = new int[]{2,1,9,0,5,3,7,6,8}; get(data); //外層控制排序的總次數 for (int y = 0 ; y < data.length ; y++){ //內層控制每次的排序控制 for (int x = 0 ; x <data.length-1 ; x++) { if (data[x] > data[x+1]){ int t = data[x]; data[x] = data[x+1]; data[x+1] = t; } } } get(data); } //輸出數據的方法 public static void get(int temp[] ){ for (int i = 0 ; i < temp.length ; i++) { System.out.print(temp[i]+ "、"); } System.out.println(); } }
改善設計:主方法設計上是作為程序的起點,既然是起點,所有的代碼編寫一定盡量簡單,那么我們可以單獨定義方法進行復雜操作。
1 public class 數組的排序 { 2 public static void main(String[] args) { 3 int data[] = new int[]{2,1,9,0,5,3,7,6,8}; 4 get(data); 5 sort(data); 6 get(data); 7 }
8 //輸出數據的方法 9 public static void get(int temp[] ){ 10 for (int i = 0 ; i < temp.length ; i++) { 11 System.out.print(temp[i]+ "、"); 12 } 13 System.out.println(); 14 }
15 //負責排序的方法 16 public static void sort(int s[]){ 17 //外層控制排序的總次數 18 for (int y = 0 ; y < s.length ; y++){ 19 //內層控制每次的排序控制 20 for (int x = 0 ; x <s.length-1 ; x++) { 21 if (s[x] > s[x+1]){ 22 int t = s[x]; 23 s[x] = s[x+1]; 24 s[x+1] = t; 25 } 26 } 27 } 28 } 29 }
2.數組轉置
- 原始數據 : 1 、 2 、3 、4 、5 、6 、7 、8 ;
- 轉置后數據 : 8 、 7 、6 、5 、4 、3 、2 、1 ;
要實現轉置的操作有兩個思路:
定義一個新的數組,而后將原始數組按照排序的方式插入到新的數組之中,隨后改變原始數組的引用;
1 public class 數組的排序 { 2 public static void main(String[] args) { 3 int data[] = new int[]{1,2,3,4,5,6,7,8}; 4 //首先定義一個新的數組,長度與原始數組一致 5 int temp[] = new int[data.length]; 6 int foot = data.length -1 ; 7 //對於新的數組按照索引由小到大的順序循環 8 for (int i = 0 ; i < temp.length ; i++) { 9 temp[i] = data[foot]; 10 foot--; 11 } 12 data = temp; //data轉向temp ,而data的原始數據就成為了垃圾 13 get(data); 14 15 } 16 //輸出數據的方法 17 public static void get(int temp[] ){ 18 for (int i = 0 ; i < temp.length ; i++) { 19 System.out.print(temp[i]+ "、"); 20 } 21 System.out.println(); 22 } 23 }
雖然上面的算法實現了轉置的操作,但是代碼里會產生垃圾 data的原始數據就是垃圾。
- 利用算法,再一個數組上直接完成轉置操作
- 原始數據: 1 、 2 、3 、4 、5 、6 、7 、8 ; //轉換次數:數組長度 ÷ 2 記住不管數組是技術還是偶數轉置次數一樣
- 第一次轉置: 8 、 2 、3 、4 、5 、6 、7 、1 ;
- 第二次轉置 : 8 、 7 、3 、4 、5 、6 、2 、1 ;
- 第三次轉置: 8 、 7 、6 、4 、5 、3 、2 、1 ;
- 第四次轉置 : 8 、 7 、6 、5 、4 、3 、2 、1 ;
轉置:
1 public class 數組的轉置 { 2 public static void main(String[] args) { 3 int data[] = new int[]{1,2,3,4,5,6,7,8,9}; 4 reverse(data); 5 get(data); 6 } 7 //負責轉置操作 8 public static void reverse(int arr[]){ 9 int start = 0; 10 int end = arr.length -1; 11 for (int i = 0; i < arr.length/2 ; i++) { 12 int temp = arr[start]; 13 arr[start] = arr[end]; 14 arr[end] = temp; 15 start ++; 16 end --; 17 } 18 } 19 //此方法負責輸出 20 public static void get(int temp[]){ 21 for(int i = 0 ; i < temp.length ; i++) { 22 System.out.print(temp [i]+"、"); 23 } 24 System.out.println(); 25 } 26 }
