Advertisement
sashomaga

Using binary search

Jan 7th, 2013
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. //Write a program that creates an array containing all letters from the alphabet (A-Z).
  4. //Read a word from the console and print the index of each of its letters in the array
  5. class Program
  6. {
  7.     static void Main()
  8.     {
  9.       char[] alphabet = new char[26];    
  10.       for (int i = 0; i < alphabet.Length; i++)
  11.       {                  
  12.           alphabet[i] = (char)('A' + i); ;
  13.       }
  14.  
  15.       Console.Write("Input word:");
  16.       char[] input;  
  17.       input = (Console.ReadLine()).ToCharArray();
  18.  
  19.       StringBuilder builder = new StringBuilder();
  20.  
  21.       int result;
  22.       for (int i = 0; i < input.Length; i++)
  23.       {
  24.           result = binarySearch(alphabet, input[i]);
  25.           builder.Append(result).Append(" ");
  26.       }
  27.       Console.WriteLine("Word indexes: {0}",builder);
  28.  
  29.     }
  30.  
  31.     private static int binarySearch(char[] myArray, int search)
  32.     {
  33.         int start = 0;
  34.         int end = myArray.Length - 1;
  35.         int mid;
  36.         while (start <= end)
  37.         {
  38.             mid = (start + end) / 2;
  39.             if (myArray[mid] == search)
  40.             {
  41.                 return mid;
  42.             }
  43.             else if (myArray[mid] < search)
  44.             {
  45.                 start = mid + 1;
  46.             }
  47.             else
  48.             {
  49.                 end = mid - 1;
  50.             }
  51.         }
  52.         return -1; //if not found
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement