C examples for Data Structure:Search
Searches a sorted list of customer IDs in order to get credit totals
#include <stdio.h> int main()//w ww. j ava2 s .co m { int idSearch; // Customer to look for (the key) int found = 0; // 1 (true) if customer is found int id[10] = { 3, 2, 5, 1, 8, 4, 9, 10, 0, 12 }; float value[10] = { 1.101, 45.3, 1.23, 1.56, 9.08, 1.41, 3.00, 2.67, 1.31, 9.54 }; int tempID, didSwap; // For sorting float tempBal; // First, sort the arrays by customer ID */ for (int outer = 0; outer < 9; outer++) { didSwap = 0; // Becomes 1 (true) if list is not yet ordered for (int inner = outer; inner < 10; inner++) { if (id[inner] < id[outer]) { tempID = id[inner]; // Must switch both arrays tempBal = value[inner]; // or they are no longer // linked id[inner] = id[outer]; value[inner] = value[outer]; id[outer] = tempID; value[outer] = tempBal; didSwap = 1; // True because a swap took place } } if (didSwap == 0) { break; } } printf("customer number? "); scanf(" %d", &idSearch); int i = 0; for ( i = 0; i<10; i++) { if (idSearch == id[i]) { found = 1; //Yes, match flag is set to TRUE break; //No need to keep looping } if (id[i] > idSearch) { break; } } if (found) { if (value[i] > 2) { printf("\n** That customer's balance is $%.2f.\n", value[i]); } else { printf("\n**The customer's credit is good!\n"); } } else // The ID not found { printf("** incorrect customer ID."); printf("\n ID %3d was not found in the list.\n", idSearch); } return(0); }