ellapt

T7.14.QuickSortStrings

Jan 15th, 2013
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class QuickSortStrings
  5. {
  6. static void Main()
  7. {
  8. Console.WriteLine("Sort an array of strings using the quick sort algorithm");
  9.  
  10. // Create an unsortArr array of string strArray
  11. string[] unsortArr = { "za", "et", "xefr", "cwe", "0","mef", "qdsa", "a3e", "123","213r1fe1x" };
  12.  
  13. Console.WriteLine("unsortArr array:");
  14. for (int i = 0; i < unsortArr.Length; i++)
  15. {
  16. Console.Write(unsortArr[i] + " ");
  17. }
  18. Console.WriteLine();
  19.  
  20. // Sort the array
  21.  
  22. QuickSort(unsortArr, 0, unsortArr.Length - 1);
  23.  
  24. Console.WriteLine("Sorted array:");
  25. for (int i = 0; i < unsortArr.Length; i++)
  26. {
  27. Console.Write(unsortArr[i] + " ");
  28. }
  29. Console.WriteLine();
  30. }
  31.  
  32. // A method to sort the array of strings using the QuickSort approach (use interface IComparable)
  33.  
  34. public static void QuickSort(IComparable[] strArray, int leftSide, int rightSide)
  35. {
  36. int i = leftSide;
  37. int j = rightSide;
  38. IComparable pivot = strArray[(leftSide + rightSide) / 2];
  39.  
  40. while (i <= j)
  41. {
  42. while (strArray[i].CompareTo(pivot) < 0)
  43. {
  44. i++;
  45. }
  46.  
  47. while (strArray[j].CompareTo(pivot) > 0)
  48. {
  49. j--;
  50. }
  51.  
  52. if (i <= j)
  53. {
  54. // Swap the elements
  55. IComparable temp = strArray[i];
  56. strArray[i] = strArray[j];
  57. strArray[j] = temp;
  58. i++;
  59. j--;
  60. }
  61. }
  62.  
  63. // Recursive calls of QuickSort method
  64. if (leftSide < j)
  65. {
  66. QuickSort(strArray, leftSide, j);
  67. }
  68.  
  69. if (i < rightSide)
  70. {
  71. QuickSort(strArray, i, rightSide);
  72. }
  73.  
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment