Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: quicksort and bubblesort comparison

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    12
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question quicksort and bubblesort comparison

    Hello everyone,
    I'm having trouble with my assignment and need you're help!
    I'm supposed to write the code for bubblesort and quicksort and test them under different array sizes while recording the number of comparisons done by each algorithm (to compare efficiency). the output should be the sorted arrays for array sizes of 64 and less, and then a list of the number of comparisons for each algorithm and array size.
    The Problems I'm having:
    1- although I run the sorting algorithm, the outputed array is not sorted!
    2- I'm not sure about the code for quicksort (and where to increment for the number of comparisons). I have to use the median of three implementation.
    3- the program just freeze after displaying the "supposedly" sorted arrays. It doesn't crash, but it doesn't go on to show the number of comparisons.

    I would appreciate anyone taking the time to help me, I've been stuck on it for a while and sometimes you need another pair of eyes to see what you're missing.
    this is my code (sorry if its messy )
    import java.util.*;
     
    public class CompareSorts2
    {
    	public static int quickCount, bubbleCount; // declaring the count variables here to use them in all the methods
     
    	public static void main(String[]args)
    	{
    		int[] Asize = {16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}; // different array sizes to be tested
    		int[] quickCountArray = new int[12]; //Those arrays hold the count values for each sorting method
    		int[] bubbleCountArray = new int[12];
    		Random rand = new Random();
     
    		for(int i =0; i < Asize.length; i++)
    		{
    			int n = Asize[i]; //current array size
    			int[] array = new int[n]; // declare array with the sizes in the array Asize
    			int[] tempArray = new int[n];
     
    			for(int j =0; j < array.length; j++) // populate the array
    			{
    				array[j] = rand.nextInt(5000); // new random for each position in array 0-4999 (array to be sorted)
    			}
     
    			for(int k = 0; k < array.length; k++)
    			{
    				tempArray[k] = array[k]; //copy the array to to use it on quicksort first
    			}
    			// sorting the array using both sorting algorithms
    			quickCount = quickSort(tempArray, 0, tempArray.length-1);  // running quicksort
     
     
    			if(n <=64)
    			{
    				System.out.print("\n\nn = "+n);
    				// display sorted array using both sorting method
    				System.out.println("\nQuick Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			for(int k = 0; k < array.length; k++) 
    			{
    				tempArray[k] = array[k]; // assigning tempArray to the original array to sort it again using bubblesort
    			}
     
    			bubbleCount = bubbleSort(tempArray); // sorting with bubblesort
     
    			if(n <=64)
    			{
    				System.out.println("\nBubble Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			//Store the comparison count for each algorithm in its specified array at the i position
    			quickCountArray[i] = quickCount;
    			bubbleCountArray[i] = bubbleCount;
    		}				
     
    		// printing the comparison count as a table
    		System.out.println("\n\nArray Size\t quick Sort\t\t    Bubble Sort");
    		for(int i = 0; i < 12; i++)
    		System.out.println(Asize[i]+"\t\t\t"+quickCountArray[i]+"\t\t\t"+bubbleCountArray[i]);			
    	}
     
    	//===================================================================================================	
    	//Bubble Sort method
    	public static int bubbleSort(int[] array)
    	{
    		int n = array.length;
    		bubbleCount = 0;	 // setting the count to 0 for each time you sort
    		for(int i =0; i < n-1; i++)
    		{
    			for(int j = 0; j <(n-1-i); j++)
    			{
    				bubbleCount++; // incrementing the count each time you compare two elements
    				if(array[j+1] < array[j]) // if true, swap values
    				{
    					swap(array, j+1, i);
    				}
    			}
    		}
     
    		return bubbleCount; // return the whole array sorted
    	}
     
    	//======================================Quick Sort Method===================================================
     
    	public static int quickSort(int[] array, int low, int high)
    	{
    		int n = array.length;
    		quickCount = 0; // setting the count to 0 for each time you sort
     
    		if(low+10 > high) // switch to bubble sort if array size is less than 10
               return quickCount + bubbleSort(array);
          else 
    		{		
                // Sort low, middle, high
                int middle = (low + high)/2;
     
    				// increment count
    				quickCount++;
     
                if( array[middle] < (array[low]))
                    swap(array, low, middle);
                if(array[high] < (array[low]))
                    swap(array, low, high);
                if(array[high] > (array[middle]))
                    swap(array, middle, high);
     
                // Place pivot at position high - 1
                swap(array, middle, high-1);
                int pivot = array[high - 1];
     
                // Begin partitioning
    				int i, j;
                for(i = low, j = high - 1; ;) 
    				{
                    while(array[++i] < pivot)
                        ;
                    while(array[--j] > pivot)
                        ;
                    if(i >= j)
                        break;
                    swap(array, i, j);
           		}
     
                // Restore pivot
                swap(array, i, high-1);
     
                quickSort(array, low, i-1);    // Sort small elements
                quickSort(array, i+1, high);   // Sort large elements
     
    				return quickCount;
       	}
    	}
     
    	 public static final void swap(int[] array, int index1, int index2 ) 
    	 {
            int temp = array[index1];
            array[index1] = array[index2];
            array[index2] = temp;
        }
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,120
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: quicksort and bubblesort comparison

    program just freeze
    Are there any infinite loops? Add some printlns to track down where the code is executing so you can find the infinite loop and fix it. when you find the looping, print out the values of the variables that control the loop so you can see how their values are changing (or not changing) and stop the looping.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    12
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: quicksort and bubblesort comparison

    I think there was a problem in my swap() method, but its fixed now and the arrays are sorted.
    There are no infinite loops, but quicksort is.. well, not quick. It takes forever and doesn't return a correct comparison count (always return 1)

    I fixed a few things in the code to make it easier to debug, please take a look and tell me what you think

    import java.util.*;
     
    public class CompareSorts2
    {
    	//public static int quickCount, bubbleCount; // declaring the count variables here to use them in all the methods
     
    	public static void main(String[]args)
    	{
    		int[] Asize = {16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768};
    		int[] quickCountArray = new int[12]; //Those arrays hold the count values for each sorting method
    		int[] bubbleCountArray = new int[12];
    		Random rand = new Random();
     
    		for(int i =0; i < Asize.length; i++)
    		{
    			int n = Asize[i]; //current array size
    			int[] array = new int[n]; // declare array with the sizes in the array Asize
    			int[] tempArray = new int[n];
     
    			for(int j =0; j < array.length; j++) // populate the array
    			{
    				array[j] = rand.nextInt(5000); // new random for each position in array 0-4999
    			}
     
    			for(int k = 0; k < array.length; k++)
    			{
    				tempArray[k] = array[k];
    			}
     
    			quickCountArray[i] = quickSort(tempArray, 0, tempArray.length-1); 
     
     
    			if(n <=64)
    			{
    				System.out.print("\n\nn = "+n);
    				System.out.println("\nQuick Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			for(int k = 0; k < array.length; k++)
    			{
    				tempArray[k] = array[k];
    			}
     
    			bubbleCountArray[i] = bubbleSort(tempArray);
     
    			if(n <=64)
    			{
    				System.out.println("\nBubble Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			System.out.println("\n\nArray Size\t quick Sort\t\t    Bubble Sort");
    			System.out.println(Asize[i]+"\t\t\t"+quickCountArray[i]+"\t\t\t"+bubbleCountArray[i]);	
    		}				
    		/* temporarly removed for diagnosis
    		// printing the comparison count as a table
    		System.out.println("\n\nArray Size\t quick Sort\t\t    Bubble Sort");
    		for(int i = 0; i < 12; i++)
    		System.out.println(Asize[i]+"\t\t\t"+quickCountArray[i]+"\t\t\t"+bubbleCountArray[i]);		
    		*/	
    	}
     
    	//===================================================================================================	
    	//Bubble Sort method
    	public static int bubbleSort(int[] array)
    	{
    		int n = array.length;
    		int bubbleCount = 0;	 // setting the count to 0 for each time you sort
    		for(int i =0; i < n-1; i++)
    		{
    			for(int j = 0; j <(n-1-i); j++)
    			{
    				bubbleCount++; // incrementing the count each time you compare two elements
    				if(array[j+1] < array[j]) // if true, swap values
    				{
    					swap(array, j+1, j);
    				}
    			}
    		}
     
    		return bubbleCount; // return the whole array sorted
    	}
     
    	//======================================Quick Sort Method===================================================
     
    	public static int quickSort(int[] array, int low, int high)
    	{
    		int n = array.length;
    		int quickCount = 0; // setting the count to 0 for each time you sort
     
    		if(low+10 > high) // switch to bubble sort if array size is less than 10
               return quickCount + bubbleSort(array);
          else 
    		{		
                // Sort low, middle, high
                int middle = (low + high)/2;
     
    				// increment count
    				quickCount++;
     
                if( array[middle] < (array[low]))
                    swap(array, low, middle);
                if(array[high] < (array[low]))
                    swap(array, low, high);
                if(array[high] > (array[middle]))
                    swap(array, middle, high);
     
                // Place pivot at position high - 1
                swap(array, middle, high-1);
                int pivot = array[high - 1];
     
                // Begin partitioning
    				int i, j;
                for(i = low, j = high - 1; ;) 
    				{
                    while(array[++i] < pivot)
                        ;
                    while(array[--j] > pivot)
                        ;
                    if(i >= j)
                        break;
                    swap(array, i, j);
           		}
     
                // Restore pivot
                swap(array, i, high-1);
     
                quickSort(array, low, i-1);    // Sort small elements
                quickSort(array, i+1, high);   // Sort large elements
     
    				return quickCount;
       	}
    	}
     
    	 public static final void swap(int[] array, int x, int z ) 
    	 {
    		 	int temp = array[x];
    			array[x] = array[z];
    			array[z] = temp;
        }
    }


    --- Update ---

    Oh, I forgot to tell. Quick sort should switch to bubble sort when there are only 10 or less items to be sorted, but it should still count the number of comparisons

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,120
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: quicksort and bubblesort comparison

    Have you solved your problem? If not, please explain what the problem is now.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Sep 2012
    Posts
    12
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: quicksort and bubblesort comparison

    no, its not completely solved yet! here is what's wrong:

    1- quick sort still takes forever for larger array sizes (I don't think it is supposed to).
    2- comparison count returned by quicksort is always 1

    Can you help?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,120
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: quicksort and bubblesort comparison

    The count variable is a local variable whose value is lost on recursive calls.
    One solution is to make it a static class variable.

    For testing shorten the Asize array.
    One measure of method execution would be to time its duration by using the System.currentTimeMillis() values.

    To find the problem, continue adding println method calls that show time or elapse time.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Sep 2012
    Posts
    12
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: quicksort and bubblesort comparison

    Thanks Norm. This code is full of mistakes, i'm finding out, but i've been fixing them one by one.
    I think I fixed the counts, but I broke some other stuff on the way
    Quick sort is now giving me an error that I can't seem to fix. Are you familiar with quick sort and median of three partitioning?

    the error I get is an java.lang.ArrayIndexOutOfBoundsException: -1, I looked and tried many codes for quicksort that I fount on the internet but I always get this error.
    Do you have any idea on how to fix it? are you familiar with the algorithm?

    import java.util.*;
     
    public class CompareSorts2
    {
    	public static int quickCount; // declaring the count variables here to use them in all the methods
     
    	public static void main(String[]args)
    	{
    		int[] Asize = {16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768};
    		int[] quickCountArray = new int[12]; //Those arrays hold the count values for each sorting method
    		int[] bubbleCountArray = new int[12];
    		Random rand = new Random();
     
    		for(int i =0; i < Asize.length; i++)
    		{
    			int n = Asize[i]; //current array size
    			int[] array = new int[n]; // declare array with the sizes in the array Asize
    			int[] tempArray = new int[n];
     
    			for(int j =0; j < array.length; j++) // populate the array
    			{
    				array[j] = rand.nextInt(5000); // new random for each position in array 0-4999
    			}
     
    			for(int k = 0; k < array.length; k++)
    			{
    				tempArray[k] = array[k];
    			}
     
    			if(n <=64)
    			{
    				System.out.print("\n\nn = "+n);
    				System.out.println("\nArray before Quick Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			quickCountArray[i] = quickSort(tempArray, 0, tempArray.length-1, 0);			
     
    			if(n <=64)
    			{
    				System.out.print("\n");
    				System.out.println("\nAfter Quick Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			for(int k = 0; k < array.length; k++)
    			{
    				tempArray[k] = array[k];
    			}
     
    			if(n <=64)
    			{
    				System.out.print("\n");
    				System.out.println("\nArray before Bubble Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    			//bubbleCountArray[i] = bubbleSort(tempArray, 0);
     
    			if(n <=64)
    			{
    				System.out.println("\nAfter Bubble Sort:");
    				for(int y = 0; y < n; y++)
    				{
    					System.out.print(tempArray[y]+" ");
    				}
    			}
     
    		}	
     
    		// printing the comparison count as a table
    		System.out.println("\n\nArray Size\t Quick Sort\t\t    Bubble Sort");
    		for(int i = 0; i < 12; i++)
    		System.out.println(Asize[i]+"\t\t\t"+quickCountArray[i]+"\t\t\t"+bubbleCountArray[i]);		
     
    	}
     
    	//===================================================================================================	
    	//Bubble Sort method
    	public static int bubbleSort(int[] array, int count)
    	{
    		int n = array.length;
    		//bubbleCount = count;	 // setting the count to 0 for each time you sort
    		for(int i =0; i < n-1; i++)
    		{
    			for(int j = 0; j <(n-1-i); j++)
    			{
    				count++; // incrementing the count each time you compare two elements
    				if(array[j+1] < array[j]) // if true, swap values
    				{
    					swap(array, j+1, j);
    				}
    			}
    		}
     
    		return count; // return the whole array sorted
    	}
     
    	//======================================Quick Sort Method===================================================
     
    	public static int quickSort(int[] array, int left, int right, int count)
    	{
    		//int n = right - left +1; //array size
    		quickCount = count+1; // setting the count to 0 for each time you sort
     
    		if(right - left > 10) // switch to bubble sort if array size is less than 10
          {		
             int median = partition(array, left, right);
     
    	      quickSort(array, left, median-1, quickCount);    // Sort small elements
    	      return quickSort(array, median+1, right, quickCount);   // Sort large elements	
       	}
     
          else 
    		{
    			int[] newArray = new int[10];
    			int j = 0;
    			for(int i = left; i <= right; i++)
    			{
    				int temp = array[i];
     
    				newArray[j] = temp;
    				j++;
    			}
    			System.out.println("\nArray to be switched to Bubblesort:");
    			for(int y = 0; y <10; y++)
    				{
    					System.out.print(newArray[y]+" ");
    				}
    			return bubbleSort(newArray, quickCount);
    		}
    	}
     
    	public static int partition(int[] array, int left, int right)
    	{
    		int pivot = (left + right) / 2;
     
    		int i = left;
    		int j = right+1;
     
    		while(i < j)
    		{
    			while(array[++i] < pivot)
    			;
    			while(array[--j] > pivot)
    			;
    			if(i >= j)
    	      	break;
     
    			swap(array, i, j);
     
    		}
    		swap(array, i, j); // undo last swap when i >=j
    		swap(array, left, j);
     
    		return j;
    	}
     
    	 public static final void swap(int[] array, int x, int z ) 
    	 {
    		 	int temp = array[x];
    			array[x] = array[z];
    			array[z] = temp;
        }
     
    }

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,120
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: quicksort and bubblesort comparison

    java.lang.ArrayIndexOutOfBoundsException: -1,
    Check how the index's value is created so it stays in range. You need to look at why the index is -1

    I don't know the algorithm.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Help me, java quicksort!
    By Joeyeyey in forum What's Wrong With My Code?
    Replies: 7
    Last Post: January 30th, 2013, 09:11 AM
  2. Quicksort
    By wholegrain in forum Java Theory & Questions
    Replies: 7
    Last Post: February 12th, 2012, 07:31 PM
  3. Bubblesort of an ArrayList with objects
    By bondage in forum Algorithms & Recursion
    Replies: 9
    Last Post: January 4th, 2012, 10:51 AM
  4. QuickSort method
    By D3158 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: June 15th, 2011, 09:17 PM
  5. StackOverflowError when using quicksort
    By Mathew.Williams in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 22nd, 2011, 05:24 PM