Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class List
- {
- int n;
- private int count = 0;
- int[] list;
- delegate int searchNumber(int search);
- public List()
- {
- //default size = 5
- list = new int[5];
- }
- public List(int number)
- {
- n = number;
- list = new int[n];
- }
- ~List()
- {
- //destroy list
- list = null;
- }
- public void Add(int number)
- {
- if(count < n)
- {
- list[count] = number;
- count++;
- }
- else
- {
- Console.WriteLine("Error, list is full");
- }
- }
- public void Clear()
- {
- for(int i = 0; i < list.Length; i++){
- list[i] = 0;
- }
- count = 0;
- }
- public void Display()
- {
- for(int i = 0; i < list.Length; i++)
- {
- Console.WriteLine(list[i]);
- }
- }
- private void BubbleSort()
- {
- int temp;
- for(int i = 0; i < list.Length; i++)
- {
- for(int j = 0; j < list.Length - 1 - i; j++)
- {
- if(list[j] > list[j + 1])
- {
- temp = list[j];
- list[j] = list[j + 1];
- list[j + 1] = temp;
- }
- }
- }
- }
- private void InsertionSort()
- {
- int temp;
- for(int i = 1; i < list.Length; i++)
- {
- for(int j = i; j > 0; j--)
- {
- if(list[j] < list[j - 1])
- {
- temp = list[j];
- list[j] = list[j - 1];
- list[j - 1] = temp;
- }
- }
- }
- }
- private void SelectionSort()
- {
- int temp, smallestIndex, minIndex;
- for(int i = 0; i < list.Length; i++)
- {
- smallestIndex = i;
- for(minIndex = i + 1; minIndex < list.Length; i++)
- {
- if(list[minIndex] < list[smallestIndex])
- {
- smallestIndex = minIndex;
- }
- }
- temp = list[smallestIndex];
- list[smallestIndex] = list[i];
- list[i] = temp;
- }
- }
- private int linearSearch(int key)
- {
- int location = -1;
- for(int i=0; i < list.Length; i++)
- {
- if(key == list[i])
- {
- location = i;
- break;
- }
- }
- return location;
- }
- private int binarySearch(int key)
- {
- int first = 0;
- int last = list.Length - 1;
- int middle;
- while(first < last)
- {
- middle = (first + last) / 2;
- if(key == list[middle])
- {
- return middle;
- }
- else if(key < list[middle])
- {
- last = middle - 1;
- }
- else
- {
- first = middle + 1;
- }
- }
- return -1;
- }
- public void Sort(string sortName)
- {
- Action sort;
- switch (sortName.ToLower())
- {
- case "bubble":
- sort = BubbleSort;
- sort();
- break;
- case "insertion":
- sort = InsertionSort;
- sort();
- break;
- case "selection":
- sort = SelectionSort;
- sort();
- break;
- default:
- Console.WriteLine("Error, wrong sort algorithm");
- break;
- }
- }
- public void Search(string searchName, int i)
- {
- switch (searchName.ToLower())
- {
- case "linear":
- searchNumber ls = new searchNumber(linearSearch);
- Console.WriteLine("Position: {0}", ls(i));
- break;
- case "binary":
- searchNumber bs = new searchNumber(binarySearch);
- Console.WriteLine("Position: {0}", bs(i));
- break;
- default:
- Console.WriteLine("Error, wrong search algorithm");
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement