• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

교수님이 해주신 Selection sort 반복문 중에 이해 안가는게 있습니다.

19.03.20 09:56 작성 조회수 255

0

for (int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)

{

if (array[smallestIndex] > array[currentIndex])

{

smallestIndex = currentIndex;

}

}

    array[smallestIndex] = array[currentIndex]; 이 문장이 이렇게 되야 하지 않고

smallestIndex = currentIndex; 이렇게 해서 결과 값을 도출했는지 의아합니다.

교수님이 설명하신 swap기능은 이해가 가는데,

두 피연산자들을 비교할때 있는 smallestIndex = currentIndex; 이 부분은 잘 이해가 안갑니다..

답변 3

·

답변을 작성해보세요.

1

홍길동님의 프로필

홍길동

2020.12.17

디버깅하면 알 수 있어요!

smallestIndex = currentIndex  는 말그대로 정수형 상수값을 current에서 small로 대입한 것이고,

array[smallestIndex] = array[currentIndex] 는 만약 small이 0이고 current가 1이라면 array[0]의 배열에 array[1]의 원소를 대입시킨 것이라 값이 다릅니다.

이미 질문자님을 알고 계시겠지만, 저를 위해서 남겨둬요!

0

김승원님의 프로필

김승원

질문자

2019.03.20

for (int startIndex = 0; startIndex < length - 1; ++startIndex)

{

int smallestIndex = startIndex;

    for (int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)

{

if (array[smallestIndex] > array[currentIndex])

{

smallestIndex = currentIndex;

}

}

int temp = array[smallestIndex];

array[smallestIndex] = array[startIndex];

array[startIndex] = temp;

printArray(array, length);

}

교수님이 작성하신 Selection Sort 포문에서

for (int startIndex = 0; startIndex < length - 1; ++startIndex)

{

int smallestIndex = startIndex;

    for (int currentIndex = startIndex + 1; currentIndex < length; ++currentIndex)

{

if (array[smallestIndex] > array[currentIndex])

{

array[smallestIndex] = array[currentIndex];

}

}

int temp = array[smallestIndex];

array[smallestIndex] = array[startIndex];

array[startIndex] = temp;

printArray(array, length);

}

이런 식으로 작성해봣는데 결과값이 이상하게 떠서요... 왜그런지 잘 모르겠습니다..

array[smallestIndex] = array[currentIndex];

smallestIndex = currentIndex;

이 두개의 차이점이 뭔지 잘 모르겠습니다..

0

어떻게 이해가 안가시는를 적어주셨으면 조금 더 구체적으로 도와드릴 수 있겠지만, 일단 일반적인 말씀을 드리자면 array에서 가장 작은 값을 갖는 index를 추적하기 위해서 유지하는 부분인데, 최소값이나 최대값 찾을 때 많이 사용합니다. 원 교재의 해당 부분 링크도 남깁니다. 그 외에 selection sort관련된 동영상 등을 찾아보시는 것도 도움이 될겁니다. 보통 정렬은 자료구조 과목에서 자세히 배웁니다.

https://www.learncpp.com/cpp-tutorial/64-sorting-an-array-using-selection-sort/