基础视频学习刚学到两个排序方法...
- //冒泡法排序
- class Bubblesort
- {
- public static void main(String args[])
- {
- int [] arr={5,1,6,4,2,8,9};
- bubble(arr);
- printarray(arr);
- }
- public static void bubble(int[] arr)
- {
- for (int i=0;i<arr.length-1 ;i++ )
- {
- for (int y=0;y<arr.length-i-1 ; y++) //让每一次比较的元素减少,-1是为了防止数组角标越界;
- {
- if(arr[y]>arr[y+1]) //相邻两元素相比
- {
- int temp = 0;
- temp = arr[y];
- arr[y] = arr[y+1] ;
- arr[y+1] = temp;
- }
- }
- }
- }
- public static void printarray(int[] arr)
- {
- for (int i=0;i<arr.length ;i++ )
- {
- if(i!=arr.length-1)
- System.out.print(arr[i]+",");
- else
- System.out.println(arr[i]);
- }
- }
- }
- //选择排序
- public class Demo6 {
- public static void main(String[] args) {
- int []age = {1,2,36,363,56,95,12,32,1232,3263};
-
- for (int i = 0; i < age.length; i++) {
- for (int j = i+1; j <= age.length-1; j++) {
- if(age[i] > age[j]){
- int temp = age[i];
- age[i] = age[j];
- age[j] = temp;
- }
- }
- }
- System.out.println(Arrays.toString(age));
- }
- }
- //输出为:[1, 2, 12, 32, 36, 56, 95, 363, 1232, 3263]
复制代码 |