1.准备一个RArray数组操作类:
public class RArray { private int ElementNums; private int[] arr; public int upper; public RArray(int size) { upper = size - 1; ElementNums = 0; arr = new int[size]; } public void Insert(int num) { arr[ElementNums] = num; ElementNums++; } public void DisPlayElements() { for (int i = 0; i < upper; i++) { Console.WriteLine(arr[i]); } } public void Clear() { for (int i = 0; i < upper; i++) { arr[i] = 0; ElementNums = 0; } } public int this[int index] { get { return arr[index]; } set { arr[index] = value; } } }
2.随机产生10个数字加入到RArray数组中
RArray arr = new RArray(10); Random r = new Random(100); for (int i = 0; i < 10; i++) { arr.Insert(r.Next(0, 100)); } arr.DisPlayElements();
3.使用冒泡排序的方式排序随机数
static RArray BubbleSort(RArray arr) { for (int i = 0; i <= arr.upper; i++) { for (int j = i; j <= arr.upper-1; j++) { if(arr[i]>arr[j]) { int temp = 0; temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } return arr; }
第二种写法:
static RArray BubbleSort(RArray arr) { for (int i = arr.upper; i >= 0; i--) { for (int j = 0; j < i; j++) { if (arr[i] > arr[j]) { int temp = 0; temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } return arr; }
4.测试
Console.WriteLine("Bubble Sort....."); RArray list = BubbleSort(arr); list.DisPlayElements(); Console.ReadKey();