有什么设计网站推荐,做国外服务器网站,wordpress 锚文本,备案空壳网站通知1.java 数组冒泡排序 排序的基本原理#xff08;升序#xff09;#xff1a; 原始数据#xff1a; 2 、1 、9 、0 、5 、3 、7 、6 、8#xff1b; 第一次排序#xff1a; 1 、2 、0 、5 、3 、7 、6 、8 、9 #xff1b; 第二次排序#xff1a; 1 、0 、2 、… 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[x1]){int t data[x];data[x] data[x1];data[x1] 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[x1]){
22 int t s[x];
23 s[x] s[x1];
24 s[x1] 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 } 转载于:https://www.cnblogs.com/Tsukasa/p/7090900.html