This might be a bad question but I am curious.
I was following some data structures and algorithms courses online, and I came across algorithms such as selection sort, insertion sort, bubble sort, merge sort, quick sort, heap sort.. They almost never get close to O(n) when the array is reverse-sorted.
I was wondering one thing: why are we not using space in return of time?
When I organise something I pick up one, and put it where it belongs to. So I thought if we have an array of items, we could just put each value to the index with that value.
Here is my implementation in Swift 4:
let simpleArray = [5,8,3,2,1,9,4,7,0] let maxSpace = 20 func spaceSort(array: [Int]) -> [Int] { guard array.count > 1 else { return array } var realResult = [Int]() var result = Array<Int>(repeating: -1, count: maxSpace) for i in 0..<array.count{ if(result[array[i]] != array[i]){ result[array[i]] = array[i] } } for i in 0..<result.count{ if(result[i] != -1){ realResult.append(i) } } return realResult } var spaceSorted = [Int]() var execTime = BenchTimer.measureBlock { spaceSorted = spaceSort(array: simpleArray) } print("Average execution time for simple array: \(execTime)") print(spaceSorted) Results I get:
Does this sorting algorithm exist already?
Is this a bad idea because it only takes unique values and loses the duplicates? Or could there be uses for it?
And why can't I use Int.max for the maxSpace?
Edit: I get the error below
error: Execution was interrupted.
when I use let maxSpace = Int.max
MyPlayground(6961,0x7000024af000) malloc: Heap corruption detected, free list is damaged at 0x600003b7ebc0 * Incorrect guard value: 0 MyPlayground(6961,0x7000024af000) malloc: * set a breakpoint in malloc_error_break to debug
Thanks for the answers
