solidityでクイックソート
storage領域はめっちゃ書き換えるより最後に完成品を代入したほうがよさそう。
詳しいことは知らないけれど。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
pragma solidity ^0.4.18; contract Quicksort { uint[] private storageInt; function getRandomIntArray(uint _num) private view returns(uint[]) { uint[] memory a = new uint[](_num); for(uint i=0; i<_num; i++){ a[i] = uint(keccak256(now/2 + i)) % 10; } return a; } function getStorageInt() public view returns(uint[]) { return storageInt; } function Quicksort() public { uint num = 30; storageInt = getRandomIntArray(num); } function setRandomInt_StorageInt() public returns(uint[]) { uint num = 30; storageInt = getRandomIntArray(num); return storageInt; } function getCloneArray(uint[] a) private pure returns(uint[]) { return a; } function swap(uint[] a, uint l, uint r) private pure { uint t = a[l]; a[l] = a[r]; a[r] = t; } function getPivot(uint a, uint b, uint c) private pure returns(uint) { if(a > b){ if(b > c){ return b; }else{ return a > c ? c : a ; } }else{ if(a > c){ return a; }else{ return b > c ? c : b ; } } } function quicksort(uint[] a) private pure { uint left = 0; uint right = a.length - 1; quicksort_core(a, left, right); } function quicksort_core(uint[] a, uint left, uint right) private pure { if(right <= left){ return; } uint l = left; uint r = right; uint p = getPivot(a[l], a[l+1], a[r]); while(true){ while(a[l] < p){ l++; } while(p < a[r]){ r--; } if(r <= l){ break; } swap(a, l, r); l++; r--; } quicksort_core(a, left, l-1); quicksort_core(a, r+1, right); } function getSortedArray() public view returns(uint[]) { uint[] memory a = getCloneArray(storageInt); quicksort(a); return a; } function sort_storageInt() public returns (uint[]) { uint[] memory a = getCloneArray(storageInt); quicksort(a); storageInt = a; return storageInt; } } |