制御文しかしらない人を対象とした課題の解答。
public class BubbleSortSample { public static void main(String[] args) { int[] numbers = { 5, 3, 2, 1, 4 }; for (int i = 0; i < numbers.length; i++) { int unsortedLength = numbers.length - i; for (int j = 0; j < unsortedLength - 1; j++) { if (numbers[j + 1] < numbers[j]) { int temporary = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temporary; } } } for (int i : numbers) { System.out.println(i); } } }
public class LinearSearchSample { public static void main(String[] args) { int[] numbers = { 5, 4, 2, 1, 3 }; int target = 3; int index = -1; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == target) { index = i; break; } } if (index == -1) { System.out.println(target + "は見つかりませんでした。"); } else { System.out.println(target + "は" + (index + 1) + "番目にあります。"); } } }
public class BinarySearchSample { public static void main(String[] args) { int[] numbers = { 1, 2, 3, 4, 5 }; int target = 3; int index = -1; int startIndex = 0; int endIndex = numbers.length - 1; while (startIndex <= endIndex) { int centerIndex = (startIndex + endIndex) / 2; if (numbers[centerIndex] == target) { index = centerIndex; break; } else if (numbers[centerIndex] < target) { startIndex = centerIndex + 1; } else { endIndex = centerIndex - 1; } } if (index == -1) { System.out.println(target + "は見つかりませんでした。"); } else { System.out.println(target + "は" + (index + 1) + "番目にあります。"); } } }