Advertisement
Guest User

manualSortCSharp

a guest
Dec 16th, 2011
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using System;
  2.  
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("Sorting numbers in ascending order.");
  8.         // int[] unsorted = {7, 2, 5, 4, 9, 1, 6, 3, 8};
  9.         // int[] unsorted = {9, 8, 7, 6, 5, 4, 3, 2, 1};
  10.         int[] unsorted = {4, 3, 2, 1};
  11.         int tmp = 0, pass = 0, swaps = 0;
  12.         int unsortedNumLen = unsorted.Length;
  13.        
  14.         DisplayResults("\nNumbers unsorted.", unsorted);
  15.        
  16.         //sort
  17.         while(pass != unsortedNumLen)
  18.         {
  19.             for(int i=0,j=1; i < unsortedNumLen-1 && j < unsortedNumLen; i++,j++)
  20.             {
  21.                 if (unsorted[i] > unsorted[j])
  22.                 {
  23.                     pass = 0;
  24.                     swaps++;
  25.                     Console.Write("Swapping {0} and {1}:\t", unsorted[i], unsorted[j]);
  26.                     tmp = unsorted[i];
  27.                     unsorted[i] = unsorted[j];
  28.                     unsorted[j] = tmp;
  29.                     printArray(unsorted);
  30.                 }
  31.  
  32.                 else pass++;
  33.             }
  34.         }
  35.        
  36.         DisplayResults("\nNumbers sorted.", unsorted);
  37.         Console.WriteLine("Number of swaps: {0}\n",swaps);
  38.      
  39.     }
  40.    
  41.     static void printArray(int[] numbers)
  42.     {
  43.         foreach(int num in numbers)
  44.             Console.Write("{0} ", num);        
  45.         Console.WriteLine();
  46.     }
  47.    
  48.     static void CurrentTimeStamp()
  49.     {
  50.         Console.Write(" ({0})\n",DateTime.Now);        
  51.     }
  52.    
  53.     static void DisplayResults(string msg, int[] unsorted)
  54.     {
  55.         Console.Write(msg);
  56.         CurrentTimeStamp();
  57.         Console.WriteLine();
  58.         printArray(unsorted);
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement