Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace _2015_C_sharp_Exam
- {
- class Program
- {
- static void SortArray(int[] arr)
- {
- for (int i = 0; i < arr.Length; i++)
- {
- for (int y = 0; y < arr.Length - 1; y++)
- {
- if (arr[y] > arr[y + 1])
- {
- int temp = arr[y];
- arr[y] = arr[y + 1];
- arr[y + 1] = temp;
- }
- }
- }
- }
- static int BinarySearch(int[] arr, int start, int end, int value)
- {
- while (start <= end)
- {
- int mid = (start + end) / 2;
- if (arr[mid] == value)
- {
- return mid;
- }
- else if (value < arr[mid])
- {
- end = mid - 1;
- }
- else
- {
- start = mid + 1;
- }
- }
- return -1;
- }
- static void Main(string[] args)
- {
- //Question 3 - a
- Console.Write("Enter the size of the array : ");
- int Size = int.Parse(Console.ReadLine());
- int[] arr = new int[Size];
- Console.WriteLine("Enter the array elements : ");
- for (int i = 0; i < Size; i++)
- {
- arr[i] = int.Parse(Console.ReadLine());
- }
- Console.Write("Originial array : ");
- for (int i = 0; i < Size; i++)
- {
- Console.Write(arr[i] + " ");
- }
- SortArray(arr); //bubble sort
- Console.WriteLine(); //newline
- Console.Write("Sorted array : ");
- for (int i = 0; i < Size; i++)
- {
- Console.Write(arr[i] + " ");
- }
- Console.WriteLine();
- Console.Write("Enter the value you want to search for in the array : ");
- int SearchValue = int.Parse(Console.ReadLine());
- int position = BinarySearch(arr, 0, Size - 1, SearchValue);
- if (position == -1)
- {
- Console.WriteLine("Value not found");
- }
- else
- {
- Console.WriteLine("Found value at element " + position);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement