int n = Integer.parseInt(br.readLine()); String[] tmp = br.readLine().split(" "); int[] arr = Arrays.asList(tmp).stream().mapToInt(x -> Integer.parseInt(x)).toArray();
printIntArray(arr); for (int i = 1; i < n; i++) { int v = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > v) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = v; printIntArray(arr); } }
privatestaticvoidprintIntArray(int[] arr){ StringBuilder s = new StringBuilder(); for (int i = 0; i < arr.length; i++) { s.append(arr[i]); if (i < arr.length - 1) { s.append(" "); } } System.out.println(s.toString()); } }
🐹 Rubyコード
while n = gets.to_i breakif n == 0 arr = gets.split(' ').map(&:to_i)
0.upto(arr.size - 1) do|i| v = arr[i] j = i - 1 while j >= 0 && arr[j] > v arr[j+1] = arr[j] j -= 1 end arr[j+1] = v puts arr.join(' ') end end