Interview Questions

Java - Bubble Sorting

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */


/**
 * This class describes the code logic for Bubble Sorting.
 */

public class BubbleSort
{
    public static void main(String args[]) throws Exception
    {
        System.out.println("Bubble Sorting Demo...");
        // Define an integer array with un-sorted values
        int arrayList[] = { 45, 10, 90, 5, 500, 60 };
        int length = arrayList.length;

        // Printing the Un-Sorted array
        System.out.println("\nUn-Sorted Array:");
        for (int i = 0; i < length; i++)
        {
            System.out.println(arrayList[i]);
        }

        // Performing Bubble sorting
        for (int i = 0; i < length; i++)
        {
            for (int j = 1; j < (length - i); j++)
            {
                if (arrayList[j - 1] > arrayList[j])
                {
                    int tmpValue = arrayList[j - 1];
                    arrayList[j - 1] = arrayList[j];
                    arrayList[j] = tmpValue;
                }
            }
        }

        // Printing the Sorted array
        System.out.println("\nSorted Array:");
        for (int i = 0; i < length; i++)
        {
            System.out.println(arrayList[i]);
        }
    }
}

Output:

Bubble Sorting Demo...

Un-Sorted Array:
45
10
90
5
500
60

Sorted Array:
5
10
45
60
90
500