Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Reccursion issue with QuickSort algorithm

$
0
0
Hi all. i have a little problem with my own implementation of the quickSort algorithm. i know that this is not the normal and effiecient way of implementinh this,and i know how to do it right,but i still want to do it my way because it seems that it could work that way also.
after debugging this,it seems that the code works just fine and doing all the steps without any mistakes,but the problem is that when i want to print the new ordered list (see the main method) it just prints the original unsorted list. because the recursion,the code seems to go back to where is started from.
how can i make it not do that and return me the sorted list instead?
thanks in advance!

this is the code:


public class MyQuickSort {
	
	public static int list[] = {6,5,3,1,8,7,2,4};
	
	public static boolean sorted = false;
	
	public static int[] addNumberToArray(int arr[],int num){
		int newArr[] = new int[arr.length+1];
		for(int i = 0;i<arr.length;i++){
			newArr[i] = arr[i];
		}
		newArr[newArr.length-1] = num;
		arr = newArr;
		return arr;
		
	}
	
	
	public static int[] partition(int arr[]){
		
		while(!sorted){
			int pivotIndex = (int)(arr.length/2);
			int left[] = new int[0];
			int right[] = new int[0];
		
			for(int i = 0;i<arr.length;i++){
				if(i==pivotIndex){
					continue;
				}
				else if(arr[i]<=arr[pivotIndex]){
					left = addNumberToArray(left,arr[i]);
				}
				else{
					right = addNumberToArray(right,arr[i]);
				}
			}
			int origPivot = arr[pivotIndex];
			int k = 0;
			while(k<left.length){
				arr[k] = left[k];
				k++;
			}
			arr[k] = origPivot;
			k++;
			while(k<arr.length){
				arr[k] = right[arr.length-arr.length-(left.length+1)+k];
				k++;
			}
			if(left.length>1){
				partition(left);
			}
			if(right.length>1){
				partition(right);
			}
			if(left.length<=1&&right.length<=1){
				sorted = true;
			}
		}
			return arr;

	}



	public static void main(String[] args) {
		list = partition(list);
		for(int i = 0;i<list.length;i++){
			System.out.print(list[i]+" ");
		}
	

	}

}


Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>