SHARE
TWEET

BucketSort for float

michalkowalczyk Dec 8th, 2018 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. """
  3. Spyder Editor
  4.  
  5. This is a temporary script file.
  6. """
  7.  
  8. def bucket_sort(alist):
  9.     largest = max(alist)
  10.     length = len(alist)
  11.     size = largest/length
  12.  
  13.     buckets = [[] for _ in range(length)]
  14.     for i in range(length):
  15.         j = int(alist[i]/size)
  16.         if j != length:
  17.             buckets[j].append(alist[i])
  18.         else:
  19.             buckets[length - 1].append(alist[i])
  20.  
  21.     for i in range(length):
  22.         insertion_sort(buckets[i])
  23.  
  24.     result = []
  25.     for i in range(length):
  26.         result = result + buckets[i]
  27.  
  28.     return result
  29.  
  30. def insertion_sort(alist):
  31.     for i in range(1, len(alist)):
  32.         temp = alist[i]
  33.         j = i - 1
  34.         while (j >= 0 and temp < alist[j]):
  35.             alist[j + 1] = alist[j]
  36.             j = j - 1
  37.         alist[j + 1] = temp
  38.  
  39.  
  40. alist=[]
  41. from random import random    
  42. for i in range(0,100):
  43.     alist.append(random()*100)
  44.  
  45. print(alist)
  46. print()
  47. sorted_list = bucket_sort(alist)
  48. print('Sorted list: ', end='')
  49. print(sorted_list)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top