Algorithms
Imal Perera  

Sorting an array without using array length and without using loops

Spread the love

Recently one of my friend who just passed out of the university went to an interview and there the interviewer asked him to write an sorting algorithm without using array length as well as without using for or while loops.

Here is the algorithm I came up, there can be various ways you can solve this but in this approach I’m implementing the bubble sort using two recursive methods


public static void main(String[] args) {

		int a[] = new int[]{4, 7, 3, 67,9, 23, 15, 45};
		a = sort(0 ,a);

		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i]);
		}
	}

	public static int[] sort(int x , int a[]){
		try {
			int i = a[x];
			a = sortsupport(x,x ,a);
			sort(++x , a);
		} catch (Exception e) {

		}
		return a;
	}

	public static int[] sortsupport(int index , int itr,  int a[]){
		int ln = 0;
		try {
			int x = a[index];
			int y = a[index+1];
			ln = index;

			if(x < y){
				a[index+1] = x;
				a[index] = y;
			}
			sortsupport(++index , itr , a);

		} catch (Exception e) {
			int sorted = a[index];
			int notsorte = a[itr];
			a[itr] = sorted;
			a[index] = notsorte;
		}
		return a;
	}

Leave A Comment