Created
December 14, 2017 08:31
-
-
Save subhodi/b3b86cc13ad2636420963e692a4d896f to your computer and use it in GitHub Desktop.
Quick sort in Solidity for Ethereum network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity ^0.4.18; | |
contract QuickSort { | |
function sort(uint[] data) public constant returns(uint[]) { | |
quickSort(data, int(0), int(data.length - 1)); | |
return data; | |
} | |
function quickSort(uint[] memory arr, int left, int right) internal{ | |
int i = left; | |
int j = right; | |
if(i==j) return; | |
uint pivot = arr[uint(left + (right - left) / 2)]; | |
while (i <= j) { | |
while (arr[uint(i)] < pivot) i++; | |
while (pivot < arr[uint(j)]) j--; | |
if (i <= j) { | |
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); | |
i++; | |
j--; | |
} | |
} | |
if (left < j) | |
quickSort(arr, left, j); | |
if (i < right) | |
quickSort(arr, i, right); | |
} | |
} |
This can help possibly
contract QuickSort {
function quickSort(uint[] memory arr) public pure returns (uint[] memory) {
if (arr.length <= 1) {
return arr;
}
quickSortImpl(arr, 0, int(arr.length - 1));
return arr;
}
function quickSortImpl(uint[] memory arr, int left, int right) private pure {
if (left < right) {
int pivotIndex = partition(arr, left, right);
if (pivotIndex > 1) {
quickSortImpl(arr, left, pivotIndex - 1);
}
if (pivotIndex + 1 < right) {
quickSortImpl(arr, pivotIndex + 1, right);
}
}
}
function partition(uint[] memory arr, int left, int right) private pure returns (int) {
uint pivot = arr[uint(right)];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[uint(j)] <= pivot) {
i++;
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
}
}
(arr[uint(i + 1)], arr[uint(right)]) = (arr[uint(right)], arr[uint(i + 1)]);
return i + 1;
}
}
This takes 350K gas with 100 elements
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've implemented a bubble sort: https://gist.github.com/gsscoder/24e09900a30c7c057bbd5bc2dfb9219f