Thread: terminate a bubble sort

  1. #1
    Registered User
    Join Date
    Apr 2010
    Posts
    5

    terminate a bubble sort

    My bubble sort finishes before the loop finishes, so I get some unless printout. Is there a way I terminate my bubble sort early if no more swaps is being made with code without using bool?

    Code:
    void sortlist(int nums[],int size)
    	{
    		
    		for(int index = 0 ; index < size-1; index++)		
    		{		
    			if (nums[index] > nums[index+1])
    			{				
                     
    			   int temp = nums[index+1];   
    	    nums[index+1] = nums[index];               
    	      nums[index] = temp;		   	  
    			
    			}
    
    		}
     printlist(nums,size);
    	}

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Don't call printlist() inside sortlist() perhaps?

    Besides, I thought a bubble sort had two nested loops, and you only have one.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bubble sort not working... wats d prob?
    By Huskar in forum C Programming
    Replies: 8
    Last Post: 03-31-2009, 11:59 PM
  2. help with debug (bubble sort algorithm)
    By lbraglia in forum C Programming
    Replies: 5
    Last Post: 10-19-2007, 05:24 PM
  3. Bubble Sort... which type?
    By gflores in forum C++ Programming
    Replies: 8
    Last Post: 08-15-2004, 04:48 AM
  4. Bubble Sort, Qucik Sort
    By insomniak in forum C Programming
    Replies: 2
    Last Post: 03-15-2003, 04:54 PM
  5. Help with Bi-Directional Bubble Sort in C
    By cunninglinguist in forum C Programming
    Replies: 0
    Last Post: 04-19-2002, 02:32 PM