Java - Selection, Bubble, Insertion Sort Algorithms

Byul·2023년 6월 6일

Java

목록 보기
1/10

import java.util.Arrays;

public class SortAlgorithms {

	public static void main(String[] args) {
		System.out.println(Arrays.toString(new SelectionSort().sort(new int[] { 5, 4, 3, 2, 1 })));
	}
}

class SelectionSort implements Sort {
	@Override
	public int[] sort(int[] nums) {
		for (int i = 0; i < nums.length; i++) {
			for (int j = i + 1; j < nums.length; j++) {
				if (nums[i] > nums[j]) {
					int temp = nums[i];
					nums[i] = nums[j];
					nums[j] = temp;
				}
			}
		}
		return nums;
	}
}

class BubbleSort implements Sort {
	@Override
	public int[] sort(int[] nums) {
		for (int i = 0; i < nums.length - 1; i++) {
			for (int j = 0; j < nums.length - 1 - i; j++) {
				if (nums[j] > nums[j + 1]) {
					int temp = nums[j];
					nums[j] = nums[j + 1];
					nums[j + 1] = temp;
				}
			}
		}
		return nums;
	}
}

class InsertionSort implements Sort {
	@Override
	public int[] sort(int[] nums) {
		for (int i = 1; i < nums.length; i++) {
			int key = nums[i];
			int j;
			for (j = i - 1; j > -1 && nums[j] > key; j--) {
				nums[j + 1] = nums[j];
			}
			nums[j + 1] = key;
		}
		return nums;
	}
}

interface Sort {
	public abstract int[] sort(int[] nums);
}
profile
junior backend developer

0개의 댓글