判断一个数组是否已经排好序以及二分查找

这里判断函数写成了一个模板,比较的类型T需要实现了<操作符操作。这里只测试了整形数组的排序。

 // ds00.cpp : Defines the entry point for the console application.

//

#include 
<stdio.h>
#include 
<tchar.h>
#include 
<cstdlib>
#include 
<iostream>
#include 
<sys/timeb.h>
#include 
<ctime>
#include 
<climits>
#include 
<cassert>
#include 
<cmath>

using namespace std;

//冒泡排序
void BubbleSort(int *arr,int len)
{
    //检测输入参数
    assert(arr!=NULL);

    //判断一轮检测是否有交换
    bool change = true;

    //有交换才继续排序
    for(int i= len-1; i > 1 && change; --i)
    {
        change = false;
        for(int j=0;j<i; ++j)
        {
            if(arr[j] > arr[j+1])
            {
                int tmp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = tmp;
                change = true;
            }
        }
    }
}

//模板方法,判定一个数组是否已经排好序(升序排列)
template<class T>
bool IsSorted(const T *arr,int len)
{
    bool sorted = true;

    for(int i=0;i<len-1;++i)
    {
        if(arr[i] > arr[i+1])
        {
            sorted = false;
        }
    }

    return sorted;
}

//二分查找
int binarySearch(const int *arr, int n,int val)
{
    int low = 0 , high = n - 1 , mid = 0;
    while(low < high)
    {
        mid = (low + high) / 2;
        if( val == arr[mid] ) 
        {
            return mid;
        }
        else if (val < arr[mid])
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1;
        }
    }

    //没找到
    return -1;
}

int _tmain(int argc, _TCHAR* argv[])
{   
    int n = 0;
    cout << "请输入数组的大小:";
    cin >> n;
    int *intArr = new int[n];
    for(int i=0;i<n;++i)
    {
        intArr[i] = rand() % 100;
    }

    cout << "原始的数组为:" ;
    for(int i=0;i<n;++i)
    {
        cout << intArr[i] << " ";
    }
  

    if(IsSorted(intArr,n))
    {
        cout << "该数组已经升序排列!" << endl;
    }
    else
    {
        cout << "该数组没有升序排列!" << endl;
    }

    BubbleSort(intArr,n);
    
    cout << endl << "冒泡排序的数组为:" ;
    for(int i=0;i<n;++i)
    {
        cout << intArr[i] << " ";
    }

    if(IsSorted(intArr,n))
    {
        cout << "该数组已经升序排列!" << endl;
    }
    else
    {
        cout << "该数组没有升序排列!" << endl;
    }

    int pos = binarySearch(intArr,n,36);
    if( pos != -1)
    {
        cout << "在数组中存在该值,位于数组的位置为:" << pos << endl;
    }
    else
    {
        cout << "在数组中没有找到该值。" << endl;
    }

    system("pause");
    return 0;
}

 

 

posted on 2010-10-27 11:07  虚怀若谷  阅读(2304)  评论(0编辑  收藏  举报

导航