본문 바로가기
개발공부 일지/코테

선택정렬(Selection Sort) - 자바스크립트(JS), C#(씨샵)

by Box Cat 2023. 6. 25.
728x90
반응형

자바스크립트 코드(Javascript JS)

function solution(arr) {
    let answer = arr;
    for(let i=0;i<arr.length-1;i++){
        let idx=i;
        for(let j=i+1;j<arr.length;j++){
            if(arr[j]<arr[idx]) idx=j;
        }
        [arr[i],arr[idx]] = [arr[idx],arr[i]];
    }
    return answer;
}
let arr = [13, 5, 11, 7, 23, 15];

console.log(solution(arr));
//Big-O는 n^2

설명: https://www.youtube.com/watch?v=uCUu3fF5Dws&t=15s

 
 

 

C# 코드(씨샵 CSharp)


namespace CodeTest
{
    internal class Program
    {
        static void SelectSort(int[] arr) // 선택 정렬은 idx를 바꾸는 것이 핵심!!
        {
            for (int i=0; i<arr.Length-1;i++)
            {
                int idx = i;
                for (int j = i+1; j < arr.Length - 1; j++)
                {
                    if (arr[i] > arr[j])
                    {
                        idx = j;
                        int temp = arr[i];
                        arr[i] = arr[idx];
                        arr[idx] = temp;
                    }
               
                }
            }
        }


        static void Main(string[] args)
        {
            int[] arr = { 3, 2, 1, 5, 4, 8, 7, 6, 10, 9, 11 };

            SelectSort(arr);

            foreach (var el in arr)
            {
                Console.WriteLine(el); //1 2 3 4 5 6 7 8 9 10 11
            }

        }

    }
}
728x90
반응형

댓글