Tuesday, 22 January 2013

Classical Programming - 7 : insert sort (c++)

void InsertSort(int* Data,int Count)
{
    int iTemp;
    int iPos;
    for(int i=1;i<Count;i++)
    {
        iTemp = Data[i];
        iPos = i-1;
        while((iPos>=0) && (iTemp<Data[iPos]))
        {
            Data[iPos+1] = Data[iPos];
            iPos--;
         }
            Data[iPos+1] = iTemp;
     }
 }

Classical Programming - 6 : select sort (c++)

void SelectSort(int* Data,int Count)
{
    int iTemp;
    int iPos;
    for(int i=0;i<Count-1;i++)
    {
        iTemp = Data[i];
        iPos = i;
        for(int j=i+1;j<Count;j++)
        {
            if(Data[j]<iTemp)
            {
                iTemp = Data[j];
                iPos = j;
             }
         }
         Data[iPos] = Data[i];
         Data[i] = iTemp;
     }
 }

Sunday, 30 September 2012

Classical Programming - 5 : exchange sort (c++)

void ExchangeSort(int* pData,int Count)
{
    int iTemp;
    for(int i=0;i<Count-1;i++) {
          for(int j=i+1;j<Count;j++) {
              if(pData[j]<pData[i])   {
                         iTemp = pData[i];
                         pData[i] = pData[j];
                         pData[j] = iTemp;
                  }
              }
         }
   }

Saturday, 29 September 2012

Classical Programming - 4 : bubble sort (c++)

void BubbleSort(int* Data,int Count) {
    int iTemp;
    for(int i=1;i<Count;i++) {
          for(int j=Count-1;j>=i;j--) {
                if(Data[j]<pData[j-1]) {
                        iTemp = Data[j-1];
                        Data[j-1] = pData[j];
                        Data[j] = iTemp;
                     }
              }
        }
 }



Tuesday, 13 March 2012

Classical Programming - 3 : print binary numbers (c++)

#include <iostream>
using namespace std;
#define SIZE sizeof(int)*8

char* bits(int val) {
     static char str[SIZE];
     for(int i = SIZE-1; i >= 0; i--) {      
       str[(SIZE-1)-i] = (val & (1<<i)) == 0? '0':'1';
     }
     return str;
 }

int main () { 
    int i = 2345;   
  
    cout << " i: " << bits(i) << endl;  
    return 0;
}

Monday, 12 March 2012

Classical Programming - 2 : check bit of unsigned integer (c++)

bool isOn(unsigned int val, int bitNo){
  return (val>>bitNo)%2;
}

bool isOff(unsigned int val, int bitNo){
  return !isOn(val, bitNo);
}

Sunday, 12 February 2012

Classical Programming - 1 : validation (c++)

int validMonth(int mon, char* errmes){
  int res = 0;
  if(mon > 0 && mon <=12){
    res  = 1;
  }
  else{
    strcpy(errmes, "Invalid month (1<=month<=12)");
  }
  return res;
}
write the above function in one line:
int validMonth(int mon, char* errmes){
return (mon>0&&mon<=12)||(strcpy(errmes, "Invalid month (1<=month<=12)")&& 0);
}