Solidityでクイックソート
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 |
//Write your own contracts here. Currently compiles using solc v0.4.15+commit.bbb8e64f. pragma solidity ^0.4.18; contract SimpleStore { function test() public pure returns (uint[]){ uint[] memory a = new uint[](5); uint n = 5; for(uint i=0; i<a.length; i++){ a[i] = n - i; } quicksort(a); return a; } function quicksort(uint[] a) public pure { uint left = 0; uint right = a.length-1; quicksort_core(a, left, right); } function quicksort_core(uint[] a, uint left, uint right) public 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 getA() public pure returns (uint[]) { uint[] memory a = new uint[](5); for(uint i=0; i<a.length; i++){ a[i] = i; } swap(a, 0, 4); quicksort(a); return a; } function getPivot(uint a, uint b, uint c) public 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 swap(uint[] a, uint l, uint r) public pure{ uint t = a[l]; a[l] = a[r]; a[r] = t; } function increment(uint[] a) pure public { for(uint i=0; i<a.length; i++){ a[i] = 1; } } } |