Monday 19 January 2015

Implement C++/Java/Python program for bubble sort using function template.

 // b_sort.cpp
                                                                                                                                                                                                                                                                                                                                         
#include<iostream> 
#include<iostream>
using namespace std;
template <class T>
void bubble(T a[],int n)
{
    for(int i=0;i<n-1;i++)
    {
    for(int j=0;j<n-i-1;j++)
    {
        if(a[j]>a[j+1])
        {
        T temp=a[j];
        a[j]=a[j+1];
        a[j+1]=temp;
        }
    }
    }
}

        int main()
            {
                int x[5];
                float y[5];
                cout<<"Enter values of array x:\n";
                for(int i=0;i<5;i++)
                 cin>>x[i];
                cout<<"Enter values of array y:\n";
                for(int i=0;i<5;i++)
                cin>>y[i];
                bubble(x,5);
                bubble(y,5);
                cout<<"Sorted array X:";
                for(int i=0;i<5;i++)
                cout<<x[i]<<"\t";
                cout<<endl;
                cout<<"Sorted array Y:";
                for(int i=0;i<5;i++)
                cout<<y[i]<<"\t";
                cout<<endl;
                return 0;
            }


//java code

 import java.util.*;
import java.io.*;

class BubbleSort
{
  public static <T extends Comparable<T>> void bubbleSort (T[] list, int size)
  {
    T temp;
    // swapOccurred helps to stop iterating if the array gets sorted before
    // outCounter reaches to size
    for (int i=0;i<list.length;i++)
    {
      for (int j=0;j<list.length-1;j++)
      {
        if (list[j].compareTo(list[j+1]) > 0)
        {
          temp = list[j];
          list[j] = list[j+1];
          list[j+1] = temp;
        }
      }
    }
  }
}

public class BubbleSortDemo
{
  public static void main (String[] args)
  {
    Integer arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    BubbleSort.bubbleSort(arr, arr.length);

    System.out.println("Sorted Array: ");
    for(Integer i : arr)
    {
      System.out.println(i);
    }
    Double arr1[] = {10.5, 2.9, 6.8, 1.7, 6.8, 5.5, 4.4, 1.3, 2.91, 1.11};
    BubbleSort.bubbleSort(arr1, arr1.length);

    System.out.println("Sorted Array: ");
    for(Double i : arr1)
    {
      System.out.println(i);
    }


  }
}
       

1 comment:

  1. Harrah's Cherokee Casino Resort - MapyRO
    Find Harrah's 순천 출장샵 Cherokee Casino Resort, NC, United States, 경주 출장안마 United 인천광역 출장샵 States, real photos, map 김포 출장샵 and prices. Real photos, maps and 성남 출장샵 other information.

    ReplyDelete