두 번째 값부터 시작하여 앞의 값들과 비교하여 삽입할 위치를 찾아 Insert하는 정렬
구현 시뮬레이션
1. 두번 째 값(인덱스 1 - Key값)과 앞의 값을 비교
2. 앞의 값이 더 크다면 Swap
3. Step 2 : 세번째 값(인덱스 2 - Key값)과 앞의 값(인덱스 1)을 비교
4. 앞의 값이 더 크다면 Swap
5. Key 값(인덱스 1)과 앞의 값(인덱스 0)을 비교
6. 앞의 값이 더 크다면 Swap
7. Step 반복

시간복잡도
삽입 정렬은 이중 for문으로 구현되어 시간복잡도가 O(n^2)임
코드 - 이중 for문
import java.util.Arrays;
public class InsertionSort01 {
void swap(int[] arr, int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
int[] sort(int[] arr) {
for (int i = 1; i < arr.length; i++){
for (int j = i; j > 0; j--){
// 현재 값이 앞의 값보다 더 작다면 swap
if(arr[j] < arr[j-1]){
swap(arr, j, j-1);
} else{
break; // 아니라면 바로 탈출하여 시간 줄임
}
}
}
return arr;
}
public static void main(String[] args) {
int[] arr = new int[]{8, 5, 6, 2, 4};
InsertionSort01 insertionSort01 = new InsertionSort01();
int[] resultArr = insertionSort01.sort(arr);
// 배열 형태로 출력
System.out.println(Arrays.toString(resultArr));
}
}
코드 - 재귀
import java.util.Arrays;
public class InsertionSort02 {
// 재귀 활용
void swap(int[] arr, int a, int b) {
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
int[] sort(int[] arr, int i) {
// i가 arr 길이와 같아지면 arr 리턴
if (i == arr.length) return arr;
for (int j = i; j > 0; j--){
// 현재 값이 앞의 값보다 더 작다면 swap
if(arr[j] < arr[j-1]){
swap(arr, j, j-1);
} else{
break; // 아니라면 바로 탈출하여 시간 줄임
}
}
// i에 +1 해서 재귀
return sort(arr, i + 1);
}
public static void main(String[] args) {
int[] arr = new int[]{8, 5, 6, 2, 4};
InsertionSort02 insertionSort02 = new InsertionSort02();
int[] resultArr = insertionSort02.sort(arr, 1);
// 배열 형태로 출력
System.out.println(Arrays.toString(resultArr));
}
}
build.gradle에 해당 코드 넣기
tasks.withType(JavaCompile){ options.encoding = "UTF-8" }
현재 코드
public String getSqlInsertQuery() {
this.address = this.address.replace("'", "");
String query = "INSERT INTO `likelion-db`.`seoul_hospital` (`id`,`address`,`district`,`category`,`emergency_room`,`name`,`subdivision`) " +
"VALUES (\"" + this.id + "\",\"" + this.address + "\",\"" + this.district + "\",\"" + this.category + "\"," +
this.emergencyRoom + ",\"" + this.name + "\",\"" + this.subdivision + "\");";
return query;
}
String.format 사용하여 개선 코드
public String getSqlInsertQuery2() {
this.address = this.address.replace("'", "");
String query = String.format("INSERT INTO `likelion-db`.`seoul_hospital` (`id`,`address`,`district`,`category`,`emergency_room`,`name`,`subdivision`) " +
"VALUES (\"%s\",\"%s\",\"%s\",\"%s\",%d,\"%s\",\"%s\");", this.id, this.address, this.district, this.category,
this.emergencyRoom, this.name, this.subdivision);
return query;
}
🔴 + 연산자로 String을 구성할 경우 실수할 수 있음 ➡String.format을 사용해라
해당 .sql 오른쪽 버튼 ➡ open in ➡ explorer
🔴 테이블 삭제할 때 신중하게 해야함
➡ DB에 영향이 큰 Query를 날리기 전에 꼭 DB를 백업하고 해야함
(나중에 개발자로 활동할 때 운영서버인지 개발서버인지 꼭 확인하고 할 것)
1. Truncate Table : 내용 삭제
2. Drop Table : 테이블 삭제
DB 사용 방법
1.
use `likelion-db`;
select count(*) from seoul_hospital;
select count(*) from `likelion-db`.seoul_hospital;
Select
database에 질문을 해서 답을 얻는 것
SELECT * FROM seoul_hospital limit 1000;*은 전체, 변수명을 써주면 그 변수만 가져옴)SELECT name FROM seoul_hospital limit 1000;Where
조건 지정
SELECT name, subdivision FROM seoul_hospital where subdivision = "안과";like
🔴 와일드 카드 : %은 개수제한 X, _
은 한자리
SELECT name, subdivision FROM seoul_hospital where subdivision = "" and name like "%이비인후과%";distinct
중복값 제거(고유값만)
변수 앞에 작성
group by
그룹으로 묶기
SELECT subdivision, count(subdivision) as cnt FROM seoul_hospital group by subdivision order by cnt desc;Update
데이터 변경
UPDATE seoul_hospital SET subdivision = "이비인후과" where subdivision = "" and name like "%이비인후과%";🔴 Safe Mode에 걸려서 Update와 Delete가 안될 경우
Edit ➡ Preferences ➡ SQL Editor ➡ Safe Updates 체크 해제
(단, 위험하므로 필요시에만 사용)
병원분류명(category)이 총 몇가지 인지?
SELECT distinct category FROM seoul_hospital order by category;
병원분류별로 몇개씩 있는지? ex) 의원:x개 치과병원:y개 한방병원:z개 …
SELECT subdivision, count(subdivision) as cnt FROM seoul_hospital group by subdivision order by cnt desc;
병원 분류가 몇가지 인지?
SELECT count(distinct subdivision) FROM seoul_hospital;
서울의 구별로 각 병원이 몇개 있는지 ex) 서울시 금천구 의원, 한방병원, 치과병원, .. 이 각 몇개인지?
select district, count(district) as cnt from seoul_hospital group by district order by cnt desc;
구별로 병원이 가장 많은 구는?
SELECT district, count(district) as cnt FROM seoul_hospital group by district order by cnt DESC;
➡ 강남구
이비인후과(0), 외과(1), 내과(2), 소아과(3), 피부과, 성형외과 는 각 몇개인지
SELECT subdivision, count(subdivision) as cnt FROM seoul_hospital group by subdivision