1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
namespace SuanFa.Sequence { class BucketSort { static void Main() { //create an object BucketSort bs = new BucketSort(); bs.bucketSort(); } public void bucketSort() { //define ordered sequence int[] array = { 21, 8, 6, 11, 36, 50, 27,42,30,12 }; //define buckets,ten buckets ,the size of the bucket is ten int[,] bucket = new int[10,10]; //initialize buckets for(int i=0;i<bucket.GetLength(0);i++) { for(int j=0;j<bucket.GetLength(1);j++) { bucket[i, j] = 0; } } //sort for(int i=0;i<array.Length;i++) { int index = getIndex(array[i]); insertSort(bucket,array[i],index); } //put the ordered sequence to array int t = 0; for (int i = 0; i < bucket.GetLength(0); i++) { for (int j = 0; j < bucket.GetLength(1); j++) { if(bucket[i,j]!=0&&j!=0) { array[t] = bucket[i,j]; t++; } } } //print ordered array print(array); } //insert sort public void insertSort(int[,] array,int k,int index) { //the position of the new element int i = array[index,0] + 1; while (i>0&&k<array[index,i]) { //move the bigger element back array[index,i + 1] = array[index,i]; i--; } //save new element array[index,i + 1] = k; array[index, 0]++; } //the index of the bucket public int getIndex(int i) { return i / 10 % 10; } /// <summary> /// print /// </summary> /// <param name="nums">the array which will printed</param> public void print(int[] nums) { for (int i = 0; i < nums.Length; i++) { Console.WriteLine("i=" + nums[i] + " "); } Console.WriteLine(); } } }
|
近期评论