In this example code, the PDL comments have been highlighted
to help you identify them more easily.
/*************************************************************** The purpose of a swap sort is to put an array of numbers into sequential order. This sorting is accomplished by comparing the values of two adjacent values in the array. If the two numbers are already in proper numerical order, the numbers remain in position. If the two adjacent numbers are out of proper sequence, their positions are interchanged. The function needs to know the content of an array of numbers and the count of numbers in that array. Last modification done on: June 6, 2000. Output should look like this: Contents of original array: 8 3 5 1 Contents of swapped array: 1 3 5 8 ******************************************************************/
import java.lancs.*; public class java_code { public static void main(String[] args) { int Temp; int MAX=4; int[] ArrayToSort = {8, 3, 5, 1}; /* Print the original array contents */ System.out.println(); System.out.println("Contents of the original array: "); for (int First = 0; First < MAX; First++) { System.out.print(ArrayToSort[First] + " "); } System.out.println(); /* Loop, counting down from the count of numbers to 1 */ for (int count = (MAX-1); count > 0; count--) { /* Loop, counting from 1 to the current value of the outer loop counter */ for (int index = 0; index < (MAX-1); index++) { /* (Assuming the value of the inner loop index is n:) */i /* If the nth element in the array is larger than the (n+1)th element */ if (ArrayToSort[index] > ArrayToSort[index+1]) { /* Assign the nth array element to a temporary variable */ Temp = ArrayToSort[index]; /* Assign the (n+1)th array element to the nth array element */ ArrayToSort[index] = ArrayToSort[index+1]; /* Assign the temporary variable to the (n+1)th element in the array */ ArrayToSort[index+1] = Temp; } /* End if */ } /* End loop */ } /* End loop */ /* Print the sorted array contents */ System.out.println(); System.out.println("Contents of swapped array:"); for (int NewFirst = 0; NewFirst < MAX; NewFirst++) { System.out.print(ArrayToSort[NewFirst] + " "); } System.out.println(); System.out.println(); } }
Created by
Allan Caine,
Laura Drever,
Gorana Jankovic,
Megan King,
and
Marie Lewis.
Revised by
Vince Sorensen
and
Mandy Aldcorn.
Last Modified: June 8, 2000
Copyright 2000
Department of Computer Science, University of Regina.