go to  ForumEasy.com   
JavaPro
Home » Archive » Message


[Email To Friend][View in Live Context][prev topic « prev post | next post » next topic]
  Insertion Sort -- O(n^2)
 
Subject: Insertion Sort -- O(n^2)
Author: Alex_Raj
In response to: Sort Algorithms
Posted on: 12/27/2013 01:59:13 AM

/**
 *  Average case performance: O(n^2)
 *  Best case performance:    O(n)
 *  Worst case performance:   O(n^2)
 */
public class InsertionSort {

    /**
     * @param a Array of integers which are sorted when returns.
     */
    public static void sort(int[] a)
    {
        if(a==null||a.length==0)
            return;
        
        int temp;
        for(int k=1; k<a.length; k++){
            temp = a[k];
            int j;
            for(j=i; j>0 && a[j-1]>temp; j--){
                a[j]=a[j-1];
            }
            a[j]=temp;
        }
    }
}


 

> On 12/27/2013 01:58:01 AM Alex_Raj wrote:


Bubble Sort -- O(n^2)
/**
 *  Average case performance: O(n^2)
 *  Best case performance:    O(n)
 *  Worst case performance:   O(n^2)
 */
public class BubbleSort {

    /**
     * @param a Array of integers which are sorted when returns.
     */
    public static void sort(int[] a)
    {
        if(a==null||a.length==0)
            return;
        
        int temp;
        for(int k=a.length; k>1; k--){
            for(int j=1; j<i; j++){
                if(a[j]<a[j-1]){
                    temp = a[j-1]; 
                    a[j-1] = a[j];
                    a[j] = temp;
                }
            }
        }
    }
}





References:

 


 
Powered by ForumEasy © 2002-2022, All Rights Reserved. | Privacy Policy | Terms of Use
 
Get your own forum today. It's easy and free.