winforms - Randomly Generate Numbers for Bubble Sort Algorithm without Duplicates in Windows Forms C#? -
i practicing bubble sort algorithm in windows forms. have gotten program point algorithm works, , can generate numbers in listbox 1-100 in non-numerical order, , run bubble sort algorithm sort numbers. problem i'm having don't want duplicate numbers generating in listbox. basically, have radio button produces 100 integers in listbox when clicked. have "sort" button sort through numbers in listbox. using arrays this, array easiest use when writing bubble sort algorithm , creating random numbers in listbox (that's why i'm not creating new list , attempting shuffle way). if has suggestions prevent duplicates, i'd appreciate it. here excerpt of code below.
int[] array; int smallmaxsize = 101; #region sort button click private void button1_click(object sender, eventargs e)//bubblesort code { bubblesortalgorithm(smallmaxsize); } #endregion #region swap numbers private void swap(int one, int two)//swaps larger number smaller number { int temp = array[one]; array[one] = array[two]; array[two] = temp; } #endregion #region bubble sort algorithm private void bubblesortalgorithm(int size) { int out; int in; (out = size - 1; out > 1; out--) { (in = 0; in < out; in++) { if (array[in] > array[in + 1]) { swap(in, in + 1); numbers.items.clear(); (int = 0; < size; i++) { numbers.items.add(array[i]); } } } } } #endregion #region small max: 100 private void radiobutton1_checkedchanged(object sender, eventargs e)//max 100 button { numbers.items.clear(); array = new int[smallmaxsize]; random numgenerator = new random(); numgenerator.next(smallmaxsize); (int = 0; < 101; i++)//generates 100 random numbers 1-100 { array[i] = numgenerator.next(smallmaxsize); numbers.items.add(array[i]); } } #endregion
when need generate 100 random numbers 1 100, inclusive, no duplicates, generating them numgenerator.next(smallmaxsize)
, checking duplicates inefficient. better approach fill array 100 numbers want, in sorted order, , apply shuffle algorithm list.
this q&a explains how shuffle list using fisher-yates algorithm.
Comments
Post a Comment