Showing posts with label bubble sort. Show all posts
Showing posts with label bubble sort. Show all posts

Sunday, January 19, 2014

Sort a linked list using bubble sort

Merge sort looks like a best choice for sorting the linked list.At a first appearance, merge sort may be a good  selection since the middle element is required to subdivide the given list into 2 halves, but we can easily solve this problem by moving the nodes alternatively to 2 lists.
We have discussed the sorting options for linked list here. Here we will discuss about bubble sort

Pseudocode for bubble sort:
public void sortList()
{
    if (isEmpty())
    {
        System.out.println("An empty list is already sorted");
    }
    else if (getHead().getNext() == null)
    {
        System.out.println("A one-element list is already sorted");
    }
    else
    {
        Node current = getHead();
        boolean swapDone = true;
        while (swapDone)
        {
            swapDone = false;
            while (current != null)
            {
                if (current.getNext() != null && current.getData().getSurname().compareTo(current.getNext().getData().getSurname()) >0)
                {
                    CustomerFile tempDat = current.getData();
                    current.setData(current.getNext().getData());
                    current.getNext().setData(tempDat);
                    swapDone = true;
                }
                current = current.getNext();
            }
            current = getHead();
        }
    }
}

Source-http://stackoverflow.com/questions/7168164/sorting-linked-lists-in-c/7168300#7168300

Bubble sort on double linked list

 Following can be the pseudocode:
public void bubbleSort() {
    boolean done = false;
    while (!done) {
        Node cur = head;
        done = true;
        while(cur != tail) {
            if (cur.getNext().getCount()>cur.getCount()) {
                swap(cur.getNext(),cur);
                done=false;
            }
            cur = cur.getNext();
        }
    }
}

Thanks.
Source : stackoverflow

What's the fastest algorithm for sorting a linked list?

Merge sort is the best choice. At a first appearance, merge sort may be a good  selection since the middle element is required to subdivide the given list into 2 halves, but we can easily solve this problem by moving the nodes alternatively to 2 lists.

It is reasonable to expect that you cannot do any better than O(N log N) in running time, whenever we use comparison based sorts.

However, the interesting part is to investigate if you can sort it in-place, stably, and so on.

Auxiliary storage requirement is small and constant (i.e. a few variables within the sorting routine). Thanks to the inherently different behaviour of linked lists from arrays, this Mergesort implementation avoids the O(N) auxiliary storage cost normally associated with the algorithm.

It may be possible, depending on a number of factors, it may actually be faster to copy the list to an array and then use a Quicksort.
The reason this might be faster is that an array has much better cache performance than a linked list. If the nodes in the list are dispersed in memory, you may be generating cache misses all over the place. Then again, if the array is large you will get cache misses anyway.
Mergesort parallelises better, so it may be a better choice if that is what you want. It is also much faster if you perform it directly on the linked list.
Since both algorithms run in O(n * log n), making an informed decision would involve profiling them both on the machine you would like to run them on.

 Here are some methods for sorting on linked list:
You can apply the sorting algorithms on double link list as well:

Thanks.

Thursday, January 14, 2010

Bubble sort

The sorting problem
Input: Array of numbers , unsorted. Eg.

Output : Same numbers sorted in some order, say increasing order. Eg.



What is Bubble Sort?

The bubble sort works by comparing each item in the list with the item next to it, and swapping them if required. The algorithm repeats this process until it makes a pass all the way through the list without swapping any items (in other words, all items are in the correct order). This causes larger values to "bubble" to the end of the list while smaller values "sink" towards the beginning of the list.

Example
Consider the array - {28, 18, 7, 4, 10}
So, in first pass is bubbled at the top, it being the smallest.












Finally 4 is on top.














Now, in second pass, 10 bubbles out , it being second smallest element and so on:

Bubble sort implementation in c

void bubbleSort(int arr[], int n) {
      bool swapped = true;
      int j = 0;
      int tmp;
      while (swapped) {
            swapped = false;
            j++;
            for (int i = 0; i < n - j; i++) {
                  if (arr[i] > arr[i + 1]) {
                        tmp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = tmp;
                        swapped = true;
                  }
            }
      }
}


Bubble sort in cpp:
 #include <iostream>
 
 class BubbleSort
 {
     public:
         BubbleSort(){}
         ~BubbleSort(){}
         void sort(int arr[], int size);
 };
 
 void BubbleSort::sort(int arr[], int size)
 {
     //With every iteration in outer loop, the next maximum element is moved to it's correct position
     for(int outerLoopIdx = 0; outerLoopIdx < size ; ++outerLoopIdx)
     {
         for(int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx)
         {
             //Comparing two subsequent elements OR bubble comparison
             //Placing the larger element on the right
             if(arr[innerLoopIdx] > arr[innerLoopIdx + 1])
             {
                 int temp = arr[innerLoopIdx];
                 arr[innerLoopIdx] = arr[innerLoopIdx + 1];
                 arr[innerLoopIdx + 1] = temp;
             }
         }
     }
 }
 
 void print(int arr[], int size)
 {
     for(int i = 0; i < size; ++i)
         std::cout << arr[i] << " ";
     std::cout << std::endl;
 }
 
 int main()
 {
     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
     BubbleSort bs;
     bs.sort(arr, 9);
     print(arr, 9);
     return 0;
 }#include <iostream>
 
 class BubbleSort
 {
     public:
         BubbleSort(){}
         ~BubbleSort(){}
         void sort(int arr[], int size);
 };
 
 void BubbleSort::sort(int arr[], int size)
 {
     //With every iteration in outer loop, the next maximum element is moved to it's correct position
     for(int outerLoopIdx = 0; outerLoopIdx < size ; ++outerLoopIdx)
     {
         for(int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx)
         {
             //Comparing two subsequent elements OR bubble comparison
             //Placing the larger element on the right
             if(arr[innerLoopIdx] > arr[innerLoopIdx + 1])
             {
                 int temp = arr[innerLoopIdx];
                 arr[innerLoopIdx] = arr[innerLoopIdx + 1];
                 arr[innerLoopIdx + 1] = temp;
             }
         }
     }
 }
 
 void print(int arr[], int size)
 {
     for(int i = 0; i < size; ++i)
         std::cout << arr[i] << " ";
     std::cout << std::endl;
 }
 
 int main()
 {
     int arr[] = { 10, 65, 35, 25, 15, 75, 85, 45, 65 };
     BubbleSort bs;
     bs.sort(arr, 9);
     print(arr, 9);
     return 0;
 }

Bubble sort in java
To come

Bubble sort in java using Generics
import org.junit.Assert;
import org.junit.Test;

class GenericBubbleSorter<T extends Comparable<T>>
{
    public void sort(T[] elems) {
        int size = elems.length;

        for (int outerLoopIdx = 0; outerLoopIdx < size; ++outerLoopIdx) {
            for (int innerLoopIdx = 0; innerLoopIdx < (size - outerLoopIdx - 1); ++innerLoopIdx) {
                if (elems[innerLoopIdx].compareTo(elems[innerLoopIdx + 1]) > 0) {
                    T temp = elems[innerLoopIdx];
                    elems[innerLoopIdx] = elems[innerLoopIdx + 1];
                    elems[innerLoopIdx + 1] = temp;
                }
            }
        }
    }
}

public class BubbleSortTester
{
    private String[] unsortedNames = new String[] {
            "Pankaj",
            "Paresh",
            "Ankit",
            "Sankalp",
            "Aditya",
            "Prem",
            "Rocket",
            "Singh",
            "Alabama",
            "Alaska",
            "Animal" };

    private String[] sortedNames = new String[] {
            "Aditya",
            "Alabama",
            "Alaska",
            "Animal",
            "Ankit",
            "Pankaj",
            "Paresh",
            "Prem",
            "Rocket",
            "Sankalp",
            "Singh" };

    @Test
    public void testStringSort() {
        GenericBubbleSorter<String> bs = new GenericBubbleSorter<String>();
        bs.sort(unsortedNames);
        Assert.assertArrayEquals(unsortedNames, sortedNames);
    }
}

Thanks.