The Job Interview: Technical questions (Pt. IV)

By DimitriC at March 21, 2011 19:56
Filed Under: Programming, Training

An often requested piece of code is a sort algorithm. Of course, there are many sorting algorithms as you can see with our good friend wikipedia. A popularly one is the Bubble sort. In it’s essence it’s not a difficult algorithm once you know how it works. But in interviews it’s usually the case that you haven’t had to implement it for a long time or maybe you’ve just graduated and have never heard of it (but then you shouldn’t have graduated or the people responsible for your curriculum need a good talking to!) A good alternative for the bubble sort is the Insertion sort.

 

A short description:

 

“…a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. “ – Source: Wikipedia

The algorithm:

   1: void BubbleSort(int[] intArray)
   2: {
   3:     int tmp;
   4:     for (int i = intArray.Length - 1; i >= 0; i--)
   5:     {
   6:         for (int j = 1; j <= i; j++)
   7:         {
   8:             if (intArray[j - 1] > intArray[j])
   9:             {
  10:                 tmp = intArray[j - 1];
  11:                 intArray[j - 1] = intArray[j];
  12:                 intArray[j] = tmp;
  13:             }
  14:         }
  15:     }
  16: }

 

 

An example of using the method above:

 

   1: void Main(string[] args)
   2: {
   3:     int[] intArray = new int[] { 2, 8, 4, 9, 5, 1 };
   4:     PrintArray(intArray);
   5:     BubbleSort(intArray);
   6:     Console.WriteLine();
   7:     PrintArray(intArray);
   8:  
   9:     Console.ReadKey();
  10: }
  11:  
  12: public static void PrintArray(int[] intarray)
  13: {
  14:     foreach (int number in intarray)
  15:     {
  16:         Console.WriteLine(number);
  17:     }
  18: }

 

…gives the following output:

 

image

Comments are closed