영상
개념
<script>
/*
[문제]
a배열에 랜덤숫자(1~100) 9개 저장 후
내림차순 정렬하시오.
[예시]
정렬 전 >>>
[72, 23, 40]
[67, 62, 88]
[57, 54, 48]
b = [72, 23, 40, 67, 62, 88, 57, 54, 48]
b = [88, 72, 67, 62, 57, 54, 48, 40, 23]
정렬 후 >>>
[88, 72, 67]
[62, 57, 54]
[48, 40, 23]
*/
let a = [
[0,0,0],
[0,0,0],
[0,0,0]
];
for(let i=0; i<a.length; i++) {
for(let j=0; j<a[i].length; j++) {
a[i][j] = Math.floor(Math.random() * 100) + 1;
}
}
document.write("정렬 전 >>><br>");
for(let i=0; i<a.length; i++) {
document.write(a[i] + "<br>");
}
document.write("<br>");
// 일차원 배열에 저장후,
let b = [];
for(let i=0; i<a.length; i++) {
for(let j=0; j<a[i].length; j++) {
b.push(a[i][j]);
}
}
document.write("b = " + b + "<br>");
// 일차원 배열로 내림차순 정렬
for(let i=0; i<b.length; i++) {
let maxNum = b[i];
let maxIndex = i;
for(let j=i; j<b.length; j++) {
if(maxNum < b[j]) {
maxNum = b[j];
maxIndex = j;
}
}
let tmp = b[i];
b[i] = b[maxIndex];
b[maxIndex] = tmp;
}
document.write("b = " + b + "<br>");
// 다시 이차원 배열에 저장
let index = 0;
for(let i=0; i<a.length; i++) {
for(let j=0; j<a[i].length; j++) {
a[i][j] = b[index];
index += 1;
}
}
document.write("정렬 후 >>><br>");
for(let i=0; i<a.length; i++) {
document.write(a[i] + "<br>");
}
</script>
Java
복사