Showing posts with label Nested for Loop. Show all posts
Showing posts with label Nested for Loop. Show all posts

Saturday, August 22, 2015

Sort Word List in Ascending Order

Q. 103. C++ Program to accept 'n' Words into an array and Sort them in Ascending order.


Copy Code:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
  char a[20][50], tmp[50]; 
  int i, j, n;
  cout << "How many Words to Sort ? ";
  cin >> n;
  
  cout << "\nEnter "<< n <<" Words \n";
  for ( i=0 ; i<n ; ++i )
       cin >> a[i];

  for ( i=0 ; i < n-1 ; ++i )
      for ( j = i+1 ; j<n; ++j )
           if ( strcmp ( a[i], a[j]) > 0 )
               {
                   strcpy ( tmp, a[i] ) ;
                   strcpy ( a[i], a[j] );
                   strcpy ( a[j], tmp );
                }   

  cout << "\nSORTED LIST\n\n";
  for ( i=0 ; i<n ; ++i )
       cout << a[i] <<"\n";
  
  return 0;
}





Binary Search using Array


Q. 107. Accept 'n' numbers into an array and search for any value using Binary Search method.

Note: Condition for Binary Search is that all numbers entered into the array must be in Ascending order.


Copy Code:

#include <iostream>

using namespace std;

int main()

{

  int a[5], n, i, j, temp, s, low, high, mid;

  cout << "How many numbers would you enter ? ";

  cin >> n;

  cout << "Enter " << n <<" numbers :\n";

  for ( i=0 ; i<n ; ++i)

      cin >> a[i];

  // Sorting Array in Ascending Order for Binary Search

   for ( i=0 ; i < n-1 ; ++i )

      for ( j = i+1 ; j<n; ++j )

          if ( a[ i ] > a[ j ])

               {

                   temp = a[ i ] ; 

                   a[ i ] = a[ j ];

                   a[ j ] = temp;

                }  

  cout << "\nEnter the number to Search : ";

  cin >> s;

  low = 0;

  high = n-1;

  while (low <= high)

  {

     mid = (low + high)/2 ;

     if (s == a[mid])

       {

          cout << "\nAfter Sorting for Binary Search ";

          cout << s << " is PRESENT at Position " << mid +1;

          exit (0);

        }

      else if (s > a[mid])

              low = mid + 1;

           else 

              high = mid - 1 ;

   }

   cout << "\n" << s << " is NOT FOUND";

   return 0;

}