C指標編程之道 ---第九次筆記

來源:互聯網
上載者:User

標籤:style   io   ar   os   sp   for   strong   on   bs   

//這裡說的是指標在演算法中的應用
//直接選擇排序
//每個排序的演算法都是指標的方便性的特點來指向每個元素進行交換等
//這裡的基本思想是對待排序的記錄進行n - 1次選擇。
//第i次操作選擇i大(小)的記錄放在第i個(或者n - i - 1 個)位置上。
//即每次都將一個記錄放在它最終的位置上,
//這就是所謂的“各回各家”
#include <iostream>
#include <cstdio>
using namespace std;
void SelectSort(int *Array, int n)
{
int i, j, m, a;
//從無序的序列中找到最小值的位置
for(i = 0; i < n - 1; i++)
{
m = 1;
for(j = i + 1; j < n; ++j)
{
if(*(Array + j) < *(Array + m))
m = j;
}
/*
*記錄當前最小值的位置
* */


if(m != 1)
{
a = *(Array + m);
*(Array + m) = *(Array + 1);
*(Array + i) = a;
}
}


}






int main()
{
int i  = 0;
int Array[10] = {12, 2, 37, 67, 90, 1, 78, 67, 2, 32};
printf("待排序的數組為:\n");
for(i = 0; i < 10; ++i)
{
printf("%d\t", *(Array + i));
}
SelectSort(Array, 10);
printf("\n直接排序後的結果為:\n");
for(int j = 0; j <10; ++j)
{
printf("%d ", *(Array + j));
}
printf("\n");
return 0;

}



//尋找,其中涉及指標的位移
//尋找分為順序尋找
//折半尋找
//兒茶尋找
//分塊尋找
//這裡舉的例子是二分尋找
#include <iostream>
#include <cstdio>
using namespace std;
int BinarySearch(int * Array, int n, int x)
{
int low, high, middle;
low = 0, high = n - 1;
while(low <= high)
{
middle = (low + high)/2;
if(*(Array + middle) == x)
return 1;
else
{
if(*(Array + middle) >= x)
{
high = middle - 1;
}
if(*(Array + middle) <=x)
{
low = middle + 1;
}
}

}


}






int main()
{
int Array[10] = {2, 4, 5, 13, 15, 20, 30, 35, 40, 50};
int x1, x2;
x1 = 20;
x2 = 33;
if(BinarySearch(Array, 10, x1))
printf("已經找到%d\n", x1);
else
printf("未找到%d\n", x1);
if(BinarySearch(Array, 10, x2))
printf("已經找到%d\n", x2);
else
printf("未找到%d\n", x2);
return 0;
}

C指標編程之道 ---第九次筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.