Sorting Algorithms swift :( VIII) bucket sort

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/lin1109221208/article/details/90694110

1 Overview

Works bucket sort the array is assigned to a limited number of a bucket, a bucket and then each individual ordering that it is possible to use other sorting algorithms / recursively continue to use the bucket sort.

2, algorithm principle

Idea: the array assigned to a limited number of buckets, then look for the sequence, and the items one by one into the bucket corresponding to, for each is not empty bucket sort will eventually merge all the barrels

     1, built barrel

     2, sub-barrel

     3, sorting kegs

3, for example

To [1,34,66,90,99,34,56,2,3,47,66,99] Sort

1) Since 99 --- barrel build the largest, so the establishment of 100 empty barrel, are stored 0

2) a kit of parts to be sorted --- element as a subscript bucket, the same + 1, the value represents the number of the tub element

3) Remove the bucket is greater than the value of the subscript 0, is also desired

4, algorithm

func bucketSort(_ array : [Int], _ max : Int)->[Int]{
        var a : [Int] = [Int].init(repeating: 0, count: max)
        
        //1、创建一个空桶,全部存0
        for i in 0..<max {
            a[i] = 0
        }
        
        //2、将数组中的元素作为a的下标存储,如果有相同的,则+1
        for num in array {
            var index = NSInteger(num)
            if a[index] as! NSInteger >= 0{
                a[index] = (a[index] as! NSInteger)+1
            }else{
                a[index] = 0
            }
        }
        
        //遍历桶,根据下标取出数据并排序
        var sort = [Int]()
        for i in 0..<a.count {
            if a[i] as! NSInteger > 0 {
                if a[i] as! NSInteger > 1{
                    //处理相同数据的情况
                    for _ in 0..<a[i]{
                        sort.append(i)
                    }
                }else{
                    sort.append(i)
                }
                
            }
        }
        
        return sort
    }



调用:
        array8 = [1,34,66,90,99,34,56,2,3,47,66,99]
        array8 = bucketSort(array8, 100)


运行结果:
[1, 2, 3, 34, 34, 47, 56, 66, 66, 90, 99, 99] 

5, the time complexity

Bucket sort time complexity is O (n)

 

github Code

Note: The sort of specific implementation code in  SortSummary.swift  calling file is in ViewController.swift

Guess you like

Origin blog.csdn.net/lin1109221208/article/details/90694110