2.1 Insertion sort
Insertion Sort
#include <iostream> using namespace std; int main() { int a[]={5,2,4,6,1,3}; int n=5; for (int j=1;j<=n;++j) { int key=a[j]; int i=j-1; while (( i >= 0)&& (a[i]>key)) { a[i+1]=a[i]; --i; } a[i+1]=key; } for (int k=0;k<=5;++k) cout<<a[k]<<endl; return 0; }
Exercise 2.1-2
Rewrite the INSERTION-SORT procedure to sort into nonincreasing instead of nondecreasing order.
#include <iostream> using namespace std; int main() { int a[]={5,2,4,6,1,3}; int n=5; for (int j=1;j<=n;++j) { int key=a[j]; int i=j-1; while (( i >= 0)&& (a[i]<key)) { a[i+1]=a[i]; --i; } a[i+1]=key; } for (int k=0;k<=5;++k) cout<<a[k]<<endl; return 0; }
Exercise 2.1-3
Linear Search
/* *************************************************************************************** Linear search Input: A sequence of n numbers A=<a1,a2,...,an> and a value v. Output: An index i such that v=A[i] or the special value NIL if v does not appear in A. *************************************************************************************** */ #include <iostream> using namespace std; int main() { int a[]={5,2,4,6,1,3}; int n=5; int v; cout<<"Please Enter a number: "<< endl; cin>>v; for (int i=0;i<=n;++i) { if (a[i]==v) cout<<"V=A["<<i+1<<"]"<<endl; else cout<<" "<<endl; } return 0; }