# ---------------------------------------------------
# 														 Sort Array
# ---------------------------------------------------
#														 12.02.2011
#													Roland Pfister
#									roland_pfister@t-online.de
# ---------------------------------------------------



# No SDL in this file. You will also have to remove
# all buttons from the Settings tab in order to run
# this script.
begin;	



# The PCL part features the sort_array subroutine and
# a sample command to run it.
begin_pcl;


# ---------------------------------------------------
#
# Subroutine for sorting an array. The input argument
# has to be a 1-dimensional integer array.
sub sort_array 
	( array <int,1> & a_inp )
begin

	array <int> a_new [a_inp.count()];

	a_new[1] = a_inp[1];

	int j = 0;
	int k = 0;

	# Work through the entire array....
	loop int i = 2 until i > a_inp.count()
	begin

		# Compare each number successively with
		# each element in the new array.
		loop k = 1 until k > i
		begin

		# If the current number is smaller than 
		# the number in the new array: Move all
		# array elements 1 position to the right
		# and exit the loop.
		if a_inp[i] < a_new[k] then
			
			loop j = i until j <= k 
			begin
				a_new[j] = a_new[j-1];
				j = j - 1;
			end;
			
			a_new[j] = a_inp[i];
			
			k = i + 1;
		
		# If the end is reached without encounter-
		# ing a bigger number: Append the current
		# number to the end of the new array.
		else
		
			if k == i then
				a_new[i] = a_inp[i];
			end;
		
		end;
		
		k = k + 1;
		end;
		
		# Uncomment this bit to get step-by-step
		# feedback on the slowly forming array.
		/*
		loop int h = 1 until h > a_new.count()
		begin
			term.print(a_new[h]);
			h = h + 1;
		end;
		term.print("\n");
		if i == a_inp.count() then
			term.print("\n");
		end;
		*/
		
		i = i + 1;
	end;

	# Assign the new, structured array to
	# the input array.
	a_inp = a_new;


end;
# ---------------------------------------------------




# ---------------------------------------------------
# Create a 1-d integer source array.
array <int> a_ori [5] = {5,4,3,2,1};
a_ori.shuffle();

# Print source array.
term.print("Source array: ");
loop int i = 1 until i > a_ori.count()
begin
	term.print(a_ori[i]);
	i = i + 1;
end;
term.print("\n\n");


# Sort the array.
sort_array(a_ori);


# Print results
term.print("Sorted array: ");
loop int i = 1 until i > a_ori.count()
begin
	term.print(a_ori[i]);
	i = i + 1;
end;
# ---------------------------------------------------