Define a class pin code and store the given pin codes in a single-dimensional array. Sort these pin codes in ascending order using the Selection Sort technique only. Display the sorted array. 110061, 110001, 110029, 110023, 110055, 110006, 110019, 110033
Topic: Selection sort on an integer array
Answer
class PinCode { public static void main(String args[]) { int pin[] = {110061, 110001, 110029, 110023, 110055, 110006, 110019, 110033}; int n = pin.length, min, pos, temp;
for(int i = 0; i < n - 1; i++) { min = pin[i]; pos = i; for(int j = i + 1; j < n; j++) { if(pin[j] < min) { min = pin[j]; pos = j; } } temp = pin[i]; pin[i] = pin[pos]; pin[pos] = temp; }
System.out.println("Array elements after the sorting"); for(int i = 0; i < n; i++) System.out.print(pin[i] + " "); } }
Selection sort is a guaranteed question type, so learn the shape exactly — and note the question says "Selection Sort technique only", so a bubble sort scores nothing however correct its output.
The idea: for each position i, look through everything to its right, find the smallest value, and swap it into position i. That is one swap per pass, which is what distinguishes it from bubble sort’s many adjacent swaps.
Three details carry the marks: - the outer loop runs to n - 1, since the last element is left in place automatically - the inner loop starts at i + 1, searching only the unsorted part - you must track the POSITION (pos) as well as the minimum value, because the swap needs the index, not just the value
The swap itself uses a temporary variable: temp = a; a = b; b = temp. Forgetting temp and writing a = b; b = a; loses the first value entirely.
pin[] int[8] - the eight pin codes to be sorted n int - number of elements in the array min int - smallest value found in the unsorted part pos int - index at which that smallest value was found temp int - temporary variable used during the swap i, j int - loop variables for the passes and the inner search