

class L28 {

	// declare and intialize a size field
	static int size = 0;
	static int[] array = new int[10];

	public static void main(String[] args) {
/*
		add(1);	
		printArray();
		add(2);
		printArray();
		add(3);
		printArray();
		removeLast();
		printArray();
		removeLast();
		printArray();
		System.out.println("1 exists: " + exists(1));
		removeLast();
		System.out.println("1 exists: " + exists(1));
*/

		add(3);
		add(9);
		add(7);
		add(4);
		add(8);
		add(5);
		add(1);
		printArray();

		sort();
		printArray();

		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		add(2);	
		printArray();
	}

	// add element to the array
	// if array is full, expand the array 
	// elm hold the element to be added

	static void add(int elm) {
		
		if (size == array.length) {
			int[] newArray = new int[size*2];
			for(int i = 0; i < size; i ++) {
				newArray[i] = array[i];
			}	
			array = newArray;	
		}
		array[size] = elm;
		size++;
	}

	// remove and return the last element added
	// return -1 if the array is empty

	static int removeLast() {
		if (size == 0) {
			return Integer.MIN_VALUE;
		}
		int temp = array[size-1];
		size--;
		return temp;	
	}

	// return true if elm exists in array; otherwise return false;
	static boolean exists(int elm) {
		for(int i = 0; i < size; i++) {
			if (array[i] == elm) {
				return true;
			}
		}
		return false;	
	}

	// count returns the number of instances of the elm passed
	// to the method

	static int count(int elm) {
		int numFound = 0;
		for(int i = 0; i < size; i++) {
			if (array[i] == elm) {
				numFound++;
			}
		}
		return numFound;
	}

	static void sort() {

		if (size <= 1) {
			return;
		}

		for(int insertIdx = 1; insertIdx < size; insertIdx++) {
			int insertElm = array[insertIdx];
			int i = 0;
			for(i = insertIdx -1; i >= 0; i--) {
				if (array[i] > insertElm) {
					array[i+1] = array[i];
				}
				else {
					array[i+1] = insertElm;
					break;
				}
			}
			if (i == -1) {
				array[0] = insertElm;
			}
		}
	}

	static void printArray() {
		for(int i = 0; i < size; i++) {
			System.out.print(array[i] + " ");
		}
		System.out.println();
	}

} // end of class
