Bucket Sort Integers

Please support our C# advertiser: Programming Forums - DaniWeb Sister Site
vckicks vckicks is offline Offline Dec 3rd, 2008, 3:24 pm |
0
Bucket sort is a very simple, fast sorting algorithm specialized in integers.
Quick reply to this message  
C# Syntax
  1. public void BucketSort(int[] integers)
  2. {
  3. //Verify input
  4. if (integers == null || integers.Length == 0)
  5. return;
  6.  
  7. //Find the maximum and minimum values in the array
  8. int maxValue = integers[0]; //start with first element
  9. int minValue = integers[0];
  10.  
  11. //Note: start from index 1
  12. for (int i = 1; i < integers.Length; i++)
  13. {
  14. if (integers[i] > maxValue)
  15. maxValue = integers[i];
  16.  
  17. if (integers[i] < minValue)
  18. minValue = integers[i];
  19. }
  20.  
  21. //Create a temporary "bucket" to store the values in order
  22. //each value will be stored in its corresponding index
  23. //scooting everything over to the left as much as possible (minValue)
  24. //e.g. 34 => index at 34 - minValue
  25. List<int>[] bucket = new List<int>[maxValue - minValue + 1];
  26.  
  27. //Initialize the bucket
  28. for (int i = 0; i < bucket.Length; i++)
  29. {
  30. bucket[i] = new List<int>();
  31. }
  32.  
  33. //Move items to bucket
  34. for (int i = 0; i < integers.Length; i++)
  35. {
  36. bucket[integers[i] - minValue].Add(integers[i]);
  37. }
  38.  
  39. //Move items in the bucket back to the original array in order
  40. int k = 0; //index for original array
  41. for (int i = 0; i < bucket.Length; i++)
  42. {
  43. if (bucket[i].Count > 0)
  44. {
  45. for (int j = 0; j < bucket[i].Count; j++)
  46. {
  47. integers[k] = bucket[i][j];
  48. k++;
  49. }
  50. }
  51. }
  52. }
0
ddanbe ddanbe is offline Offline | Dec 3rd, 2008
Nice!
Have you read http://www.daniweb.com/code/snippet979.html?
Maybe you can test wich of the three is the fastest?
 
0
MosaicFuneral MosaicFuneral is offline Offline | Dec 5th, 2008
Interesting, I'll try this out.
 
 

Message:


Thread Tools Search this Thread



Tag cloud for C#
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC