1 /**
2 * 功能:完成了对所给数组进行排序;
3 *
4 * @author Administrator
5 */
6
7 public class BubbleSort
8 {
9 public BubbleSort()
10 {
11
12 }
13
14 public static void main ( String args[] )
15 {
16 int data[] = { 63, 56, 98, 12, 24 };
17
18 int n = data.length;
19
20 // bubblesort(data, n);//冒泡排序
21 //selectionSort(data, n);//选择排序
22 insertionSort(data,n);//插入排序
23 for (int i = 0; i < n; i++)
24 {
25 System.out.println(data[i]);
26
27 }
28
29 }
30
31 public static void swap ( int data[] , int i , int j )
32 {
33 int temp;
34 temp = data[i];
35 data[i] = data[j];
36 data[j] = temp;
37 }
38
39 /*
40 * 冒泡排序
41 */
42 public static void bubblesort ( int data[] , int n )
43 {
44 int numsorted = 0;
45 int index;
46 while (numsorted < n)
47 {
48 for (index = 1; index < n - numsorted; index++)
49 {
50 if (data[index - 1] > data[index])
51 swap(data, index - 1, index);
52
53 }
54 numsorted++;
55
56 }
57
58 }
59
60 /*
61 * 选择排序
62 */
63 public static void selectionSort ( int data[] , int n )
64 {
65 int numUnsorted = n;
66 int index;
67 int max;
68 while (numUnsorted > 0)
69 {
70 max = 0;
71 for (index = 1; index < numUnsorted; index++)
72 {
73 if (data[max] < data[index])
74 max = index;
75
76 }
77 swap(data, max, numUnsorted - 1);
78 numUnsorted--;
79
80 }
81 }
82
83 /*
84 * 插入排序
85 */
86 public static void insertionSort ( int data[] , int n )
87 {
88 int numSorted = 1;
89 int index;
90 while (numSorted < n)
91 {
92 int temp = data[numSorted];
93 for (index = numSorted; index > 0; index--)
94 {
95 if (temp < data[index - 1])
96 {
97 data[index] = data[index - 1];
98 } else
99 {
100 break;
101 }
102 }
103 data[index] = temp;
104 numSorted++;
105 }
106 }
107
108 }
109
posted on 2007-02-06 16:48
-274°C 阅读(1330)
评论(1) 编辑 收藏 所属分类:
JAVA