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
| let RGBData = ['R', 'G', 'B', 'R', 'R', 'G', 'B', 'R', 'R', 'G', 'B', 'R']
function sortRGB(arr) { let i, j, len, rear, front = 0 rear = arr.length - 1 len= rear + 1
for (i = front, j = 0; j < len; ) { if (arr[i] == 'R') { swap(i, front) while (arr[front] == 'R') { i++ front++ j++ } } else if (arr[i] == 'B') { swap(i, rear) while (arr[rear] == 'B') { rear-- j++ } } else { i++ j++ } } return arr }
function swap(index1, index2) { let temp temp = RGBData[index1] RGBData[index1] = RGBData[index2] RGBData[index2] = temp } console.log(sortRGB(RGBData))
}
|