码迷,mamicode.com
首页 > 编程语言 > 详细

排序法

时间:2015-03-27 22:01:21      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

选择排序法:

 1 class Sort{
 2     public static void main(String[] args) {
 3         int[] array = {3, 9, 10, 5, 48, -23};//创建并初始化数组
 4         selectSort(array);                //调用方法
 5         System.out.println();
 6     }
 7 
 8     public static void swap(int[] arr,int a,int b){
 9         int temp = arr[a];
10         arr[a] = arr[b];
11         arr[b] = temp;
12     }
13 
14     public static void selectSort(int[] arr){
15         for(int x=0; x<arr.length-1; x++)
16             for(int y=x+1; y<arr.length; y++){
17                 if (arr[x]>arr[y]){
18                     swap(arr, x, y);     //调用方法
19                 }
20             }
21         for(int i=0; i<arr.length; i++)
22         System.out.print("arr["+i+"] = "+arr[i]+" , ");  //打印输出
23     }
24 }
 1 class Sort_2{
 2     public static void main(String[] args) {
 3         int[] array = {3, 9, 10, 5, 48, -23};//创建并初始化数组
 4         selectSort_2(array);                //调用方法
 5         System.out.println();
 6     }
 7 
 8       public static void swap(int[] arr,int a,int b){
 9         int temp = arr[a];
10         arr[a] = arr[b];
11         arr[b] = temp;
12     }
13     //使用数组下标法
14     public static void selectSort_2(int[] arr){
15         for(int x=0; x<arr.length-1; x++){
16             int num = arr[x];
17             int index = x;
18             for(int y=x+1; y<arr.length; y++){
19                 if(num>arr[y]){
20                     num = arr[y];
21                     index = y;
22                 }
23             }
24             if(index!=x)
25                 swap(arr,x,index);
26         }
27         for(int i=0; i<arr.length; i++)
28         System.out.print("arr["+i+"] = "+arr[i]+" , ");  //打印输出
29     }
30 }

冒泡排序法:

 1 class Sort{
 2     public static void main(String[] args){
 3         int[] array = {3, 5, 20, -21, 26, 12};
 4         bubble(array);
 5         printArray(array);
 6         System.out.println();
 7     }
 8 
 9     public static void swap(int[] arr,int a,int b){
10         int temp = arr[a];
11         arr[a] = arr[b];
12         arr[b] = temp;
13     }
14 
15     public static void printArray(int[] arr)
16     {
17         System.out.print("[");
18         for(int x=0; x<arr.length; x++)
19         {
20             if(x!=arr.length-1)
21                 System.out.print(arr[x]+", ");
22             else
23                 System.out.println(arr[x]+"]");
24         }
25     }
26 
27     public static void bubble(int[] arr){
28         for(int x=0; x<arr.length-1; x++)
29             for(int y=0; y<arr.length-1-x; y++){
30                 if(arr[y]>arr[y+1]){
31                     swap(arr,y,y+1);
32                 }
33             }
34     }
35 }

 

排序法

标签:

原文地址:http://www.cnblogs.com/msjgodboy/p/4372789.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!