[1~] 알고리즘

이재은·2024년 5월 22일

내가 찾으려는 데이터의 위치(인덱스는?)

1강.

1. 선형검색

선형으로 나열되어 있는 데이터를 순차적으로 스캔하며 원하는 값을 찾음

2. 보초법

맨 끝 이전에서 찾으면 찾은것
맨 끝에서 찾으면 실패
마지막 인덱스에 찾으려는 값을 추가해서 찾는 과정을 생략함.

dates = [3, 2, 5, 7, 9, 1, 0, 8, 6, 4]

searchdata = int(input('찾으려는 숫자 입력 : '))
searchResultIdx = -1


dates.append(searchdata)

n= 0
#하나씩 검색해야하니까 while문

while True :

    if dates[n] == searchdata : #비교하는데
        if n != len(dates) -1: #마지막이이 아니면!
            searchResultIdx = n
            break

    n+=1

print(searchResultIdx)

2강.

2. 이진검색

정렬된 자료구조에서 중앙값과의 크고 작음을 이용해 데이터 검색

5강.

3. 순위

수의 크고 작음을 이용해 수의 순서를 정하는 것
(작은것에 하나씩 더해서)

# 0 20개 채우기
ranks = [0 for i in range(20)]
#동일 비교 문제? :
어차피 카운트 안된건 나중에 카운트됨 97 40 / 40 97나올떄 카운트

for idx, num1 in enumerate(nums):
    for num2 in nums :
        if num1 < num2 :
            ranks[idx] += 1 
print(nums)
print(ranks)
#idx와 num가져오고 rank값도 불러오기 

for idx, num in enumerate(nums):
    print(f'점수 : {num} \t rank : {ranks[idx] + 1}')

6강.

4. 버블정렬

처음부터 끝까지 차례로 비교하자
https://gmlwjd9405.github.io/2018/05/06/algorithm-bubble-sort.html

값 바꾸기
nums[j], nums[j+1] = nums[j+1], nums[j]
  1. 리스트에서 다수 랜덤 추출 (중복허용 안됨)
#random 모듈 sample 함수 
choice 함수와 다르게 지정한 숫자만큼 숫자를 추출
중복을 허용하지 않음코드를 입력하세요

#Sample larger than population or is negative
students.append(rd.sample(range(170, 185), 20))
print(students)
#얕은복사 깊은복사 
#원래 데이터를 그대로 보존하고 싶다면
import copy

def bubbleSort(ns, deepcopy = True) : #nums의 약자

    if deepcopy :
        cns = copy.copy(ns)
    else :
        cns = ns


    length = len(cns) - 1
    for i in range(length):
        for j in range(length - i):
            if cns[j] > cns[j+1]:
                cns[j], cns[j+1] = cns[j+1] , cns[j]

    return cns

8강.

5. 삽입정렬

정렬되어있는 자료 배열과 비교해서 정렬 위치를 찾는다

함수와 메소드의 차이점
append, split
https://velog.io/@yejin20/Python-%ED%95%A8%EC%88%98%EC%99%80-%EB%A9%94%EC%86%8C%EB%93%9C%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90

11강.

6. 선택정렬

1) 리스트 중에서 최솟값을 찾아 그 값을 맨 앞에 위치한 값과 2) 교체하는 방식

nums = [4,2,5,1,3] #기준이 1까지만 가면 됨
print(nums)

for i in range(len(nums)-1) : #index 3, 즉 숫자 1까지 넘어간다
    minIdx = i
	
    #값 찾기
    #최솟값 비교를 위한의 for문
    for j in range(i+1, len(nums)):
        if nums[minIdx] > nums[j] :
            minIdx = j        #cf. nums[minIdx] = nums[j] : 값을 대체해 버림
            
	#대체하기 : 0번쨰 값은 3으로 가고, 3번째 값이 0으로 옴
    
    nums[i], nums[minIdx] = nums[minIdx], nums[i] 
    print(nums)
    # tempNum = nums[i]
    # nums[i] = nums[minIdx]
    # nums[minIdx] = nums[i]

print(nums)
#deepcopy 해서 복사본으로 전달하기
result1 = sm.sortNumber(copy.deepcopy(scores)) 
#안써도됨 asc = True #deepcopy : 복사본으로 전달
print(result1)

copy.deepcopy(scores)

profile
Dare to be an optimist

0개의 댓글